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

So I am wanting to create text files that are saved in this format hour_dayofweek.txt however I am having a hard time with the variable $theTime when I want the file opened
#!/usr/bin/perl @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun); ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWee +k, $dayOfYear, $daylightSavings) = localtime(); $year = 1900 + $yearOffset; $theTime = "$hour_$weekDays[$dayOfWeek].txt"; print $theTime; open (MYFILE, '>>'$theTime); my $url = 'http://en51.tribalwars.net/map/tribe.txt'; use LWP::Simple; my $content = get $url; @array=split(/,/, $content); $n=1; $j=4; do { print MYFILE "@array[$n] @array[$j]\n"; $n=$n+5; $j=$j+5; } while ($n<=$#array); close (MYFILE);

Replies are listed 'Best First'.
Re: printing to file, which is a variable
by dasgar (Priest) on Sep 22, 2010 at 23:06 UTC

    First, I'd suggest adding use strict; and use warnings; right after the shebang line. Good debugging tools.

    Second, I'd suggest modifying your open statement to be something like:

    open(MYFILE,">>",$theTime) || die "Unable to open file '$theFile': $! +\n";

    The changes inside the parentheses might not be critical, but the die statement will let you know if there's issues with opening the file. Currently, your code is not letting you know if the file was opened successfully.

Re: printing to file, which is a variable
by Anonymous Monk on Sep 22, 2010 at 22:59 UTC
    You have a syntax error (strictures would warn you of this): open( my $filehandle, '>>', $theTime ) or die "failed to open file $theTime: $!";

    Additionally, you might find it easier to generate that timestamp with a module like DateTime: my $time = (join '_', map { $_->hour, $_->day_abbr } DateTime->now) . '.txt';

Re: printing to file, which is a variable
by zentara (Cardinal) on Sep 23, 2010 at 10:27 UTC
    Additionally, isn't the variable supposed to be a reference? Notice the \ in front of $foo
    my $foo = ''; open FILEHANDLE, '+>', \$foo or die $!;

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh