Although many of my columns deal with entire programs, I find that people still send me email about the basics. So, this month, I thought I’d address an issue that people seem to keep asking about: basic list manipulation.
Although many of my columns deal with entire programs, I find that people still send me email about the basics. So, this month, I thought I’d address an issue that people seem to keep asking about: basic list manipulation.
Your Order, Please
One very common task with lists is selection: finding items in a list that meet a particular condition. For example, let’s find all the odd elements in a list @input:
my @output; foreach (@input) { if ($_ % 2) { push @output, $_; } }
Of course, you can shorten and clean this up a bit by using a “backwards” if:
my @output; foreach (@input) { push @output, $_ if $_ % 2; }
Or you can shorten the loop up a different way using a “backwards” foreach:
my @output; $_ % 2 and push @output, $_ foreach @input;
But alas, you can’t nest the backwards if and the backwards foreach. It’s been argued that this leads to the potential for much abuse, and is thus not permitted. Even the use of and here as a stand-in for conditional execution is arguably obfuscated enough.
The previous code works, but it’s like using a hammer when a screwdriver would suffice. A more elegant solution, Perl’s grep operator does a fine job of selecting elements from a list:
my @output = grep $_ % 2, @input;
Each element…
Please log in to view this content.
Not Yet a Member?
Register with LinuxMagazine.com and get free access to the entire archive, including: