O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

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

A.5. Chapter 6

  1. Here's one way to do it:

    print reverse <>;

    You may be surprised at the brevity of this answer, but it will get the job done. Here's what is happening, from the inside out:

    1. First, the reverse function is looking for a list for its arguments. This means that the diamond operator (<>) is being evaluated in a list context. Thus, all of the lines of the files named by command-line arguments (or standard input, if none are named) are read in and massaged into a list with one line per element.

    2. Next, the reverse function reverses the list end for end.

    3. Finally, the print function takes the resulting list, and displays it.

  2. Here's one way to do it:

    @ARGV = reverse @ARGV;
    print reverse <>;
    The first line just takes any filename arguments and reverses them. That way if the user called this script with command line arguments "camel llama alpaca", @ARGV would then contain "alpaca llama camel" instead. The second line reads in all the lines in all the files in @ARGV, flips them end on end, and prints them. If no arguments were passed to the program, then as before, <> works on STDIN instead.
  3. Here's one way to do it:

    print "List of strings:\n";
    chomp(@strings = <STDIN>);
    foreach (@strings) {
        printf "%20s\n", $_;
    }

    The first line prompts for a list of strings.

    The next line reads all of the strings into one array and gets rid of the newlines at the end of each line.

    The foreach loop steps through this array, giving $_ the value of each line.

    The printf function gets two arguments: the first ...

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