"Perl for Perl Newbies" - Part 2File Input/OutputThe <FILEHANDLE> Operator

5.2. The <FILEHANDLE> Operator

Just like print can be generalised to files, so can the <> which we encountered before. If you place the name of the filehandle inside the operator, it will read a line from the file opened by that filehandle.

Here's an example, let's append the line numbers to a given file:

use strict;
use warnings;

my ($line_num, $line);

$line_num = 0;
open my $in, "<", "input.txt";
open my $out, ">", "output.txt";

while ($line = <$in>)
{
    # We aren't chomping it so we won't lose the newline.
    print {$out} $line_num, ": ", $line;
    $line_num++;
}

close ($in);
close ($out);

And the following example counts the number of lines in a file that start with the letter "A" (case-insensitive).

use strict;
use warnings;

my ($filename, $lines_num, $line, $c);

$lines_num = 0;
$filename = "input.txt";
open my $in,  "<", $filename;
while ($line = <$in>)
{
    $c = substr($line, 0, 1);
    if (lc($c) eq "a")
    {
        $lines_num++;
    }
}
close($in);

print "In " , $filename, " there are ",
    $lines_num, " lines that start with \"A\".\n";

The join("", <FILEHANDLE>) command returns the entire contents of the file from the current position onwards, and may prove to be useful. Examples for it will be given in the next section where regular expressions will be taught.


Written by Shlomi Fish