"Perl for Perl Newbies" - Part 2File Input/OutputUsing "print" with Files

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 ($l=1 ; $l <= $pyramid_side ; $l++)
{
    print {$out} "X" x $l;
    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 sequence 0, 0.1, 1, 1.1, 2, 2.1, 3, 3.1…, and to the other the sequence 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5….

use strict;
use warnings;

open my $seq1, ">", "seq1.txt";
open my $seq2, ">", "seq2.txt";

for (my $x=0 ; $x < 100 ; $x++)
{
    print {$seq1} $x, "\n";
    print {$seq2} $x, "\n";
    print {$seq1} ($x+0.1);
    print {$seq2} ($x+0.5);
    print {$seq1} "\n";
    print {$seq2} "\n";
}

close($seq1);
close($seq2);

Written by Shlomi Fish