Dual-license your content for inclusion in The Perl 5 Wiki using this HOWTO, or join us for a chat on irc.freenode.net#PerlNet.
Articles/What the Books don't Teach You
From PerlNet
What the Books Don't Teach You
by David J. Goehrig
A few weeks ago a friend asked me to help him with a perl script he was writing to generate the search results for a website. The script he had written attempted to parse XML, using regular expressions, and then split the text into substrings stored in arrays. His code was written as one would do it in javascript, with a couple nested for loops, split functions and the first few lines looked something like this:
1 if ( ! open FP, "< $filename" ) {
2 die("Failed to open $filename, $!\n");
3 }
4 my @text;
5 while (<FP>) {
6 push(@text,$_);
7 }
8 for ($line = 0; $text[$_]; $line++ ) {
9 my $story;
10 for ($j = $line; $text[$_] ne "</NEWS>\n"; $j++ ) {
11 $story .= $text[$j];
12 }
13 process($story);
14 }
15 close FP;
He then asked me how I would have written it:
1 local $/ = "</NEWS>\n";
2 open FP, "< $filename" or die "Failed to open $filename, $!\n";
3 my (@text) = <FP>;
4 process($_) for (@text);
5 close FP;
Was my answer, which left the stories in the @text array, just as he wanted for further processing. What is the difference?
One was written by a newbie, who didn't know all of the syntax, all of the vocabulary, and had worst of all listened to what Learning Perl & the Camel books said.
His responses to my lines were as follows:
- All the books said not to do that.
- He didn't realize you could use 'or' that way.
- He didn't know what <FP> returned in a list context, or even how a list context was defined. (hint, left hand side of the = determines the context).
- Opened his eyes, not just to how pleasant single line statements can be, but also to that for and foreach are the same thing.
- The only line that didn't teach the newbie a new trick.
My lines 1 & 3 removed the need for his lines 4-12, and produced a significant runtime performance improvement.
A newbie is different from a guru in that he doesn't know the shortest distance between two points. It doesn't mean they can't write working Perl. Getting to know the richness of Perl's vocabulary, syntax, and grammar takes much more time than python, lisp, or C. It is the same difference as between learning English and Perl. The more complex the language, the more expressive it is.

