The <FILEHANDLE> Operator

Contents | Up | Prev | Next

# 5.2. The <FILEHANDLE> Operator

Just like `print` can be generalized 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 I, "<", "input.txt";
    open O, ">", "output.txt";

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

    close (I);
    close (O);

And the following example counts the number of lines in a file that start with "A":

    use strict;
    use warnings;

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

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

    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.

Contents | Up | Prev | Next