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 my $out, ">", "pyramid.txt";
for($a=1 ; $a <= $pyramid_side ; $a++)
{
    print {$out} "X" x $a;
    print {$out} "\n";
}
close($out);

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...

use strict;
use warnings;

open my $seq1, ">", "seq1.txt";
open my $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);

Written by Shlomi Fish