June 2010 Archives

grep is your friend

Grep is another Perl's great built in function, one of the things I use it most is to check if I can find an element on a list. For example, instead of something like

    my $found = 0;
    foreach (@list) {
        $search eq $_ and $found++;
    }


I prefer to use something like:

    my $found = grep {$search eq $_} @list;


Code is simpler and more elegant, there's no significant performance from using one or another, although grep seems to actually run faster if you want to squeeze all the crumbs:

find_with_for  28818/s    …

Perl shebang for different versions

In a Perl script typically a shebang line is something like:

#!/usr/bin/perl


this works great if you want to use a wide, system based, Perl for your scripts. But what if you have several different installations of Perl and want to run the same script using different Perl versions without having to change the shebang line. Well, one possible and straightforward solution is to change it to something like:

#!/usr/bin/env perl


and then push the version you want to use to your $PATH environment variable. This can even be easily done based on th…

About smash

user-pic I blog about Perl.