Basic I/O
- 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:
- First, the
reversefunction 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. - Next, the
reversefunction reverses the list end for end. - Finally, the
printfunction takes the resulting list, and displays it.
- First, the
- 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",@ARGVwould 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. - 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
foreachloop steps through this array, giving$_the value of each line.The
printffunction gets two arguments: the first argument defines the format:"%20s\n"means a 20-character right-justified column, followed by a newline. - Here's one way to do it:
print "Field width: "; chomp($width = <STDIN>); print "List of strings:\n"; chomp(@strings = <STDIN>); foreach (@strings) { printf "%${width}s\n", $_; }To the previous exercise answer, we've added a prompt and response for the field width.
The other change is that the
printfformat string now contains a variable reference. The value of$widthis included into the string beforeprintfconsiders the format. Note that we cannot write this string asprintf "%$widths\n", $_; # WRONG
because then Perl would be looking for a variable named
$widths, not a variable named$widthto which we attach ans. Another way to write this isprintf "%$width"."s\n", $_; # RIGHT
because the termination of the string also terminates the variable name, protecting the following character from being sucked up into the name.