open(LOG,"logfile.txt") or die "Unable to open $logfile:$!";
print "\n";
while(<$LOG>){
print if /\berror\b/i;
}
close(LOG);
views:
95answers:
4
+1
A:
You have an error:
while (<$LOG>)
should read
while (<LOG>)
Filehandles are not variables, so no $.
jmz
2010-08-02 23:00:00
filehandles can be variables if you use lexical filehandles
xenoterracide
2010-08-02 23:05:33
+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
2010-08-03 16:31:52
+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
2010-08-02 23:23:20
+2
A:
If you wanted an even more effortless open
, you could do this:
@ARGV = 'logfile.txt';
while ( <> ) {
print if /\berror\b/i;
}
Axeman
2010-08-03 01:10:00