tags:

views:

95

answers:

4
open(LOG,"logfile.txt") or die "Unable to open $logfile:$!";
print "\n";
while(<$LOG>){
  print if /\berror\b/i;
}
close(LOG);
+1  A: 

open LOG, "logfile.txt"; while (<LOG>) { print if /\berror\b/i; }

geoffc
+1  A: 

You have an error:

while (<$LOG>)

should read

while (<LOG>)

Filehandles are not variables, so no $.

jmz
filehandles can be variables if you use lexical filehandles
xenoterracide
+1 @jmz, you are the only one (so far) to answer the question explicitly. Perhaps you should clarify that by "filehandle" you mean a dynamically scoped, literal identifier representing an open file.
pilcrow
+9  A: 

Your typo actually takes you one step closer to opening the file the right way -- namely, using the recommended 3-argument form of open.

use strict;
use warnings;

open(my $log, '<', "logfile.txt") or die "Open failed : $logfile : $!";
while (<$log>) {
    ...
}

This approach is better because your file handle can be stored in a lexically scoped variable (rather than in a global name like LOG). This provides an added benefit in automatically closing the file when the lexical variable goes out of scope. Also, lexical file handles can be passed around between subroutines using a more familiar syntax.

FM
+2  A: 

If you wanted an even more effortless open, you could do this:

@ARGV = 'logfile.txt';
while ( <> ) { 
    print if /\berror\b/i;
}
Axeman