Fozzologs

RSS Feeds

About...

These posts are the creation of Doran L. Barton (AKA Fozziliny Moo). To learn more about Doran, check out his website at fozzilinymoo.org.

Right Side

This space reserved for future use.

Some cool Perl things...

Posted: 17 November 2010 at 15:36:43

One of the many advantages of having a software developer job where you're working in a distributed, collaborative development environment is that you get to look at other people's code. What a great way to see examples of coding strategies you've never used before.

For example, today I saw where someone had used the part subroutine provided by List::MoreUtils module. The part subroutine basically splits a list into two component parts: A part that meets the condition specified and the part that does not. The example given in the List::MoreUtils documentation is pretty decent:

my $i = 0;
my @part = part { $i++ % 2 } 1 .. 8;   

The contents of @part is now two elements, each a list reference to lists containing [1, 3, 5, 7] and [2, 4, 6, 8]. The first list contains elements from the original list (1 .. 8) that basically have a remainder after division by two. The second list contains elements which do not.

You can fetch each of the resulting list references into their own scalars:

my ($odd, $even) = part { $i++ % 2 } 1 .. 8; 

Now that I'm reading that code more closely, I think I like this variation, which drops the $i iterator and uses the input list instead, better:

my ($odd, $even) = part { $_ % 2 } 1 .. 8; 

Subroutines like part are very useful and many Perl developers make the mistake of throwing together their own implementation instead of looking to CPAN. If that describes you, stop it!