Enjoy_Life wrote:
>
hi, who can tell me which is better of the following codes?
why there are different methods to read files?
thanks
1. open(INPUT, "< filedata") or die "Couldn't open filedata for reading:
$!\n";
while (<INPUT>) {
print if /blue/;
}
close(INPUT);
2. use IO::File;
$input = IO::File->new("< filedata")
or die "Couldn't open filedata for reading: $!\n";
while (defined($line = $input->getline())) {
chomp($line);
STDOUT->print($line) if $line =~ /blue/;
}
$input->close();
I suggest that best of all is:
use IO::Handle;
open my $input, '<', 'filedata' or die "Couldn't open filedata for
reading: $!";
while (my $line = <$input>) {
next unless $line =~ /blue/;
print $line;
}
Note the following:
- die() will not show the program file and line number where it was
called if there is a newline at the end of its string parameter.
- Using IO::Handle gives access to all of the modules methods even if
the file handle has been opened in the conventional way.
- Using the three-parameter open is generally considered best practice
so that filenames with ambiguous initial characters aren't opened in
the wrong mode.
- There is generally no need to close an opened file, especially an
input file, and especially when lexical file handles are used. They
will be closed automatically when the lexical goes out of scope or
when another open is performed on the same file handle.
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/