A.  Exercise Answers

Lesson 3, Lists and Arrays

  1. Here's one way to do it:

    #!/usr/bin/perl -w
    print "Enter some lines, then press Ctrl-Z:\n";	# Ctrl-D for Xnix
    @lines = <STDIN>;
    @reverse_lines = reverse @lines;
    print @reverse_lines;

    . . . or, even more simply

    #!/usr/bin/perl -w
    print "Enter some lines, then press Ctrl-Z:\n";	# Ctrl-D for Xnix
    print reverse <STDIN>;

    Most Perl programmers would prefer the second one, as long as you don't need to keep the list of lines around for later use.

  2. One way to do this is:

    print "Enter the line number: "; 
    chomp($a = <STDIN>);
    print "Enter the lines (end with ^Z):\n"; 
    @b = <STDIN>;
    print "Answer: $b[$a-1]";

    The first line prompts for a number.  The second line reads the number from standard input, and removes that pesky newline.  The third line asks for the list of strings.  And the fourth line uses the <STDIN> operator in a list context to read all of the lines until end-of-file into the array variable @b.  The final statement prints the answer, using an array reference to select the proper line.  Note that we don't have to add a newline to the end of this string, because the line selected from the @b array still has its newline ending.

    If you are trying this from a terminal configured in the most common way, you'll need to type CTRL-Z at the terminal to indicate an end-of-file.

  3. Here's one way to do it, if you want the output all on one line:

    #!/usr/bin/perl -w
    chomp(@lines = <STDIN>);
    @sorted = sort @lines;
    print "@sorted\n";

    . . . or, to get the output on separate lines:

    #!/usr/bin/perl -w
    print sort <STDIN>;