Using "print" with Files

Contents | Up | Prev | Next

# 5.1. Using "print" with Files

The print command which we encountered before can also be used to send output to files. In fact, the screen itself is a special filehandle, whose name is `STDOUT`, but since its use is so common, perl allows it to be omitted.

The syntax of printing to a file is `print File $string1, $string2, ...` . Here's a short example that prepares a file with a pyramid in it:

    #!/usr/bin/perl

    use strict;
    use warnings;

    my $pyramid_side = 20;

    open O, ">", "pyramid.txt";
    for($a=1 ; $a <= $pyramid_side ; $a++)
    {
        print O "X" x $a;
        print O "\n";
    }
    close(O);

In order to print to more than one file at once, one needs to use two separate print statements. Here's an example, that prints to one file the sequnce 1, 1.1, 2, 2.1, 3, 3.1... and to the other the sequence 1, 1.5, 2, 2.5 , 3, 3.5...

    open SEQ1, ">", "seq1.txt";
    open SEQ2, ">", "seq2.txt";

    for($a=0;$a<100;$a++)
    {
        print SEQ1 $a, "\n";
        print SEQ2 $a, "\n";
        print SEQ1 ($a+0.1);
        print SEQ2 ($a+0.5);
        print SEQ1 "\n";
        print SEQ2 "\n";
    }

    close(SEQ1);
    close(SEQ2);

Contents | Up | Prev | Next