terms5 has asked for the wisdom of the Perl Monks concerning the following question:

In the code below I'm using the join function to make one variable that contains $timeHour, seperated by :, and $timeMinute. Then I'm reading from file fileTimes to fill the array @times with previously stored times. Then I'm putting(unshift)the joined variable I just made into the array of @times and printing the updated list back into fileTimes.
My question is this: Whenever I 'cat fileTimes' the output is always on two different lines like so:
12
:34
how do I make the file take it and display it like this:
12:34
I've tried it with strings and it works fine, but not with this. Thanks!
#!/usr/bin/perl -w my @times; my $timeDisplay; my $timeMinute = `date '+%M'`; my $timeHour = `date '+%H'`; $timeDisplay = join (":", "$timeHour", "$timeMinute"); open(IN1, '<', 'fileTimes'); #fills @times with data in fileTi +mes while(my $line = <IN1>) { chomp $line; unshift(@times, $line); } close(IN1); unshift(@times, $timeDisplay); #puts in new time to queue open(FILE, ">fileTimes"); foreach my $i (@times) { #prints back into fileTimes to upda +te print FILE "$i\n"; } close(FILE);

Replies are listed 'Best First'.
Re: joining two variables and printing them to a file?
by GrandFather (Saint) on Apr 25, 2006 at 05:55 UTC

    If I modifiy your code so that it is stand alone and doesn't require external applications then I don't see the problem you describe. Can you modify this code to reproduce the error (without introducing external dependencies)?

    use strict; use warnings; my @times; my $timeDisplay; my $timeMinute = '56'; my $timeHour = '34'; while(my $line = <DATA>) { chomp $line; unshift(@times, $line); } $timeDisplay = join (":", "$timeHour", "$timeMinute"); unshift(@times, $timeDisplay); #puts in new time to queue foreach my $i (@times) { #prints back into fileTimes to update print "$i\n"; } __DATA__ 12:34 56:78

    Prints:

    34:56 56:78 12:34

    My guess is that your external application (date) is returning newlines at the end of its string. You might want to take a look at some of the Perl date and time handling functions (time, gmtime and localtime) and modules (Date::EzDate and many others) rather than calling an external application.


    DWIM is Perl's answer to Gödel
      doh! It was date that was messing me up, the POSIX thing cleared it right up! Thanks a lot! I didn't even know those functions existed, guess I have a lot of reading to do. ^_^
Re: joining two variables and printing them to a file?
by Zaxo (Archbishop) on Apr 25, 2006 at 05:49 UTC

    In line 21 you explicitly print a newline after each array element.

    You will get better use out of POSIX::strftime and perl's builtin localtime. Shelling out twice to system date to get the time in completely unnecessary.

    $ perl -MPOSIX=strftime -e'print strftime "%H:%M\n", localtime' 01:47 $
    POSIX::strftime() is like sprintf specialized for time structures.

    After Compline,
    Zaxo