13.2. Reading from file, read, eof

Once 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;
}

 
In Perl we usually care about lines of input so the above is enough.
Still some like to read files with chunks of arbitrary length.
read puts the read string to the variable passed to the function and
returns the number of characters actually read 
READ_LENGTH = read FILEHANDLE,SCALAR,LENGTH 

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)

If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed