Perl6::Junction

Today I'd like to introduce you a Perl module I really like and use a lot in my code. It's called Perl6::Junction and you can get it from CPAN.

Please have a look what it can do for you.

Perl6::Junction comes in when you're working on Arrays. For example, if you'd like to search your array if it contains a defined element, usually your code will look like this:

my @animal = ('squirrel', 'cat', 'catfish', 'sausage-dog', 'guinea pig', 'pig');

# using a foreach loop to walk trough all array elements
#
foreach my $animal ( @animal ) {

if ( $animal eq 'guinea pig' ) {

# found my lovely guinea pig in this group of animals!
last;
}
}

# you could also go and use grep to search your array
#
if ( grep(/^guinea pig$/, @animal) ) {

# found it!
}

But especially grep is not easy to use for beginners and one could make many mistakes when using it.

For example, just calling grep like grep('cat', @animal) will match every string in the array because it excepts a BLOCK or regular expression and not a string as first argument and interprets the string as 'TRUE' which matches everything.

Doing a grep(/cat/, @animal) will match every array element that contains the string 'cat'. It would match 'cat' and 'catfish' in this example.

Most of the time, this is not really what you want.

When using Perl6::Junction it becomes as easy as this:

use Perl6::Junction qw( all any none one );

my @animal = ('squirrel', 'cat', 'catfish', 'sausage-dog', 'guinea pig', 'pig');

if ( any(@animal) eq 'guinea pig' ) {

# one or more guinea pig's in the list of animals!
}

if ( one(@ainmal) eq 'guinea pig' ) {

# exactly one guinea pig in the list
}

my @herd = ('sheep', 'sheep', 'wolf', 'sheep', 'sheep');

unless ( all(@herd) eq 'sheep' ) {

# watch out!
}

Pretty nice, right? :)

If I caught your interest, please have a look at more examples in the modules documentation at CPAN.

4 Comments

I love that module. I use it constantly.

By the way, can you shoot me an email showing me exactly what you're posting? The formatting for prettyprint seems a bit messed up, so if you can show me the exact format, I might be able to see what's happening.

I love that module. I use it constantly.

By the way, can you shoot me an email showing me exactly what you're posting? The formatting for prettyprint seems a bit messed up, so if you can show me the exact format, I might be able to see what's happening.

Leave a comment

About Marc

user-pic I am a Perl developer and CPAN author. I develop software with Perl since 1996 and Perl is still one of my favorite programing languages.