;
my $random = rand(@file);
my $fortune = $file[$random];
chomp $fortune;
print $fortune, "\n";
This is what you get (or might get - it is random, after all):
> perl fortune.plx
Now I'm being shot at from both sides. That means I *must* be right.
-- Larry Wall
>
How It Works
Once we've set our record separator appropriately, most of the work is already done for us. This is how we change it:
$/ = "\n%\n";
Now a 'line' is everything up to a newline character and then a percent sign on its own and then another new line, and when we read the file into an array, it ends up looking something like this:
my @file = (
"We all agree on the necessity of compromise. We just can't agree on
when it's necessary to compromise.\n -- Larry Wall\n%\n",
"All language designers are arrogant. Goes with the territory...\n -- Larry Wall\n%\n",
...
);
We want a random line from the file. The operator for this is rand:
my $random = rand(@file);
my $fortune = $file[$random];
rand produces a random number between zero and the number given as an argument. What's the argument we give it? As you know, an array in a scalar context gives you the number of elements in the array. rand actually generates a fractional number, but when we look it up in the array, as we've seen in Chapter 3, Perl ignores the fractional part. Actually, it's more likely that in existing code you'll see those two statements combined into one, like this:
my $fortune = $file[rand @file];
Now we have our fortune, but it still has the record separator on the end, so we need to chomp to remove it:
chomp $fortune ;
Finally, we can print it back out, remembering that we need to put a new line on the end:
print $fortune, "\n";
Reading Paragraphs at a Time
If you set the input record separator, $/, to the empty string, "", Perl reads in a paragraph at a time. Paragraphs must be separated by a completely blank line, with no spaces on it at all. Of course, you can use split or similar to extract individual lines from each paragraph. This program creates a 'paragraph summary' by printing out the first line of each paragraph in a file: