开发者

Why does this program not find the word 'error' in my text file?

open(LOG,"logfile.txt") or die "Unable to open $logfile:$!";
print "\n";
while(<$LOG>){
  print if /开发者_如何转开发\berror\b/i;
}
close(LOG);


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.


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

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


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


You have an error:

while (<$LOG>)

should read

while (<LOG>)

Filehandles are not variables, so no $.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜