13.2. Reading from file, read, eofOnce the file is open for reading it behaves exactly like STDIN and we can access the same way. Example 13-1. examples/files/read_from_file.pl #!/usr/bin/perl
use strict;
use warnings;
my $filename = "input.txt";
open my $fh, "<", $filename or die $!;
my $line = <$fh>;
chomp $line;
while (my $line = <$fh>) {
chomp $line;
#...
}
open my $data, "<", $filename or die $!;
my @lines = <$data>;
chomp @lines;
foreach my $line (@lines) {
print $line;
}
Example 13-2. examples/files/read_file.pl #!/usr/bin/perl
use strict;
use warnings;
# reading in 30 characters:
open my $in, "<", $0 or die $!;
my $expected = 30;
my $buf;
my $actual = read $in, $buf, $expected;
if ($actual < $expected) {
print "reached end of file\n";
}
# returns TRUE if we are stand at or after the end of file. eof($in)
|
Follow me: