x
Loading
 Loading
Hello, Guest | Login | Register

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.

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:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Helpful Tools for Software Developers
  2. The Github Hall of Fame
  3. Book'em, Github.
  4. This Week on Github: Stupid Ruby Tricks
  5. A Veritable Scatter Shot!
Follow Linux Magazine
Rackspace