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

My code is :
#!/usr/bin/perl -w use strict; my $LOGFILE; my $line; $LOGFILE = "access.log"; open(LOGFILE) or die("Could not open log file."); foreach $line (<LOGFILE>) { # do line-by-line processing. } close(LOGFILE); I get a very surprising : $ perl prov.pl Use of uninitialized value in open at prov.pl line 7. Could not open log file. at prov.pl line 7.
I do not understand this error and I ask for the wisdom of the great Mongs. Thank you in advance. Pierre Couderc

Replies are listed 'Best First'.
Re: Use of uninitialized value in open
by Corion (Patriarch) on Jun 10, 2008 at 08:16 UTC

    Usually, Perl is right with its error message. You're not giving the filename to open and hence Perl complains that it doesn't know what to do:

    open(LOGFILE)

    You need to give open the filename to open, and I recommend using lexical filehandles if your version of Perl supports them (since 5.6.0):

    open my $fh, "<", $LOGFILE or die "Couldn't open '$LOGFILE': $!";
Re: Use of uninitialized value in open
by moritz (Cardinal) on Jun 10, 2008 at 08:34 UTC
    Corion already gave the correct answer. Let me add pointers to the documentation.

    "perldoc -f open" documents the open function.

    If you want a gentler introduction, "perldoc perlopentut" provides a nice tutorial about how to use open in its various forms. You can do much more than just opening files it ;-)

      Thank you two.
      My mistake is too that I took this snippet form the web, where it is wrong, and I did not think to suspect it...

        I suspect the web version didn't have "my $LOGFILE;".

        It's using an old syntax you'd best avoid in favour of the one Corion showed.

Re: Use of uninitialized value in open
by cdarke (Prior) on Jun 10, 2008 at 09:05 UTC
    One other thing if I may, when reporting an error from open is is usually best to include the filename and the reason for the failure ($!), for example:
    open(my $hlogfile,'<',$LOGFILE) or die "Could not open $LOGFILE: $!";
Re: Use of uninitialized value in open
by linuxer (Curate) on Jun 10, 2008 at 09:45 UTC

    Just another thing: replace that foreach with while to read from a filehandle.

    #!/usr/bin/perl use strict; use warnings; my $logfile = 'access.log'; open my $logh, '<', $logfile or die "$logfile: open failed: $!"; while ( my $line = <$logh> ) { # do line-by-line processing } close $logh or die "$logfile: close failed: $!"; # or die ... not really necessary here, but my fingers type that autom +atically nowadays...