O'Reilly logo

Intermediate Perl by Tom Phoenix, brian d foy, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Answers for Chapter 8

Exercise 1

In this exercise, we have to use three different output methods: to a file, which you're already familiar with; to a scalar (and you'll need Perl 5.8 for this); or to both at the same time. The trick is to store the output channels in the same variable that you'll use for the print statement. When the filehandle is a variable, we can put anything we like in it and decide what to put in it at runtime.

#!/usr/bin/perl
use strict;

use IO::Tee;

my $fh;
my $scalar;

print "Enter type of output [Scalar/File/Tee]> ";
my $type = <STDIN>;

if( $type =~ /^s/i ) {
        open $fh, ">", \$scalar;
        }
elsif( $type =~ /^f/i ) {
        open $fh, ">", "$0.out";
        }
elsif( $type =~ /^t/i ) {
        open my $file_fh,   ">", "$0.out";
        open my $scalar_fh, ">", \$scalar;
        $fh = IO::Tee->new( $file_fh, $scalar_fh );
        }

my $date        = localtime;
my $day_of_week = (localtime)[6];


print $fh <<"HERE";
This is run $$
The date is $date
The day of the week is $day_of_week
HERE

print STDOUT <<"HERE" if $type =~ m/^[st]/i;
Scalar contains:
$scalar
HERE

In this program, we prompt the user for the type of output, and we want her to type either "scalar", "file", or "tee". Once we read the input, we detect which one she typed by matching on the first character (using a case-insensitive match for more flexibility).

If the user chose "scalar", we open $fh to a scalar reference. If she chose "file", we open $fh to a file, as you know from before. We name the file after the program name, stored in $0, and append .out to it. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required