O'Reilly logo

Learning Perl Student Workbook, 2nd Edition by brian d foy

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

Appendix E. Answers to Chapter 5 Exercises

Answer 5.1: This one is pretty easy once you know the trick. If you use the <> operator, you can look in $ARGV to discover the current filename. The <> operator will automatically move on to the next file when it finishes one, and it will update the filename in $ARGV. You simply tack on the filename in $ARGV to the current line in $_ and print it. You don’t need a newline at the end because $_ already has it:

#!/usr/bin/perl
use strict;
use warnings;

while( <> ) { print "$ARGV: $_" }

If you didn’t know the trick, it’s not so bad. You go through each of the command-line arguments in @ARGV and store each one in $file in turn. You open each file then go through its lines and print them as you did before:

#!/usr/bin/perl
use strict;
use warnings;

foreach my $file ( @ARGV ) {
    open my( $fh ), '<', $file;

    while( <$fh> ) { print "$file: $_" }

    close $fh;
    }

A run might look like this:

$ perl ex5.1.pl cats dogs
cats: Buster
cats: Mimi
cats: Roscoe
dogs: Nicki
dogs: Addie

Answer 5.2: You can specify standard input using the virtual filename -. When the line input operator sees that filename, it starts reading from standard input:

$ perl ex5.2.pl *.pl -

You can do this in one foreach loop. You go through the files like you did in your program in Answer 5.1, but if the name of the file is -, you set the name to stdin instead of -:

#!/usr/bin/perl use strict; use warnings; foreach my $file ( @ARGV ) { open my( $fh ), '<', $file; $file = 'stdin' if $file eq '-'; ...

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