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, and 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 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!
print "Enter the line number: "; chomp($a = <STDIN>); print "Enter the lines, end with ^D:\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.
If you are trying this from a terminal configured in the most common way, you'll need to type CTRL-D at the terminal to indicate an end-of-file.
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.