home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


A.2 Chapter 3, Arrays and List Data

  1. Here's one way to do it:

    print "Enter the list of strings:\n";
    @list = <STDIN>;
    @reverselist = 
    
    reverse @list;
    print @reverselist;

    The first line prompts for the strings. The second reads the strings into an array variable. The third line computes the list in the reverse order, storing it into another variable. The final line displays the result.

    We can actually combine the last three lines, resulting in:

    print "Enter the list of strings:\n";
    print reverse <STDIN>;

    This method works because the print operator is expecting a list, and reverse returns a list - so they're happy. And reverse wants a list of values to reverse, and <STDIN> in a list context returns a list of the lines, so they're happy, too!

  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, reads it from standard input, and removes that pesky newline. The second line asks for a list of strings, then uses the <STDIN> operator in a list context to read all of the lines until end-of-file into an array variable. 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. You'll need to type CTRL-Z at the console to indicate an end-of-file.

  3. One way to do this is:

    srand;
    print "List of strings: "; @b = <STDIN>;
    print "Answer: $b[
    
    rand(@b)]";

    The first line initializes the random number generator. The second line reads a bunch of strings. The third line selects a random element from that bunch of strings and prints it.