Main Content

Perl - lists do so much more than arrays

Archive - Originally posted on "The Horse's Mouth" - 2009-03-05 08:24:04 - Graham Ellis

open (FH,"ac_20090225");
@stuff = <FH>;
@interesting = grep(/horse/i,@stuff);
print @interesting;


In Perl, an @ in front of a variable makes it into a list - and a list variable has the advantages of an array in other languages ... without the disadvantages. And it can do a lot more too.

In the example above, I've opened a large file and read THE WHOLE FILE into a list called @stuff. There's no need to say how big it will be - Perl works that out dynamically - and assigns one line of the incoming file to each list (array) element.

I've then filtered the list via Perl's built in grep function, looking for all the elements of the list which contain "horse", and putting them into another and shorter list (grep is like a filter - it selects rather than changes elements)

Finally, I've printed out just the interesting lines - the lines that contain 'horse' - from the shorter list.

The test file I used in this little example contained 147,720 lines (our daily web site log file), and the filtered output contained 782. But the script was not slow in running, because there are no loops in the script - there were just four lines to be interpreted and run, with the looping done at the efficient lower level within Perl itself.

From yesterday's Perl Programming course.