Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Answers to Chapter 5 Exercises

  1. Here’s one way to do it:

    print reverse <>;

    Well, that’s pretty simple! But it works because print is looking for a list of strings to print, which it gets by calling reverse in a list context. And reverse is looking for a list of strings to reverse, which it gets by using the diamond operator in list context. So, the diamond returns a list of all of the lines from all of the files of the user’s choice. That list of lines is just what cat would print out. Now reverse reverses the list of lines, and print prints them out.

  2. Here’s one way to do it:

    print "Enter some lines, then press Ctrl-D:\n";  # or Ctrl-Z
    chomp(my @lines = <STDIN>);
    
    print "1234567890" x 7, "12345\n";  # ruler line to column 75
    
    foreach (@lines) {
      printf "%20s\n", $_;
    }

    Here, we start by reading in and chomping all of the lines of text. Then we print the ruler line. Since that’s a debugging aid, we’d generally comment-out that line when the program is done. We could have typed "1234567890" again and again, or even used copy-and-paste to make a ruler line as long as we needed, but we chose to do it this way because it’s kind of cool.

    Now, the foreach loop iterates over the list of lines, printing each one with the %20s conversion. If you chose to do so, you could have created a format to print the list all at once, without the loop:

    my $format = "%20s\n" x @lines;
    printf $format, @lines;

    It’s a common mistake to get 19-character columns. That happens when you say to yourself,[*] “Hey, why do we ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page