Wednesday, May 7, 2008

perl: oneliner to check if a given module is installed on your system

Let's say that you want to know whether module Tie::Hash is installed. To find out, execute the following from the command line:

perl -MTie::Hash -e 1


Source

Monday, May 5, 2008

perl: testing two arrays for equivalence

How do I test whether two arrays or hashes are equal?

The following code works for single-level arrays. It uses a string-wise comparison, and does not distinguish defined versus undefined empty strings. Modify if you have other needs.

unless ( arrays_are_equal (\@tmp1, \@tmp2) ){
    print "\ntmp1 and tmp2 are not equal!\n";
}
else {
    print "\ntmp1 and tmp2 are indeed equal!\n";
}


sub arrays_are_equal {
    my ($first, $second) = @_;
    no warnings; # silence spurious -w undef complaints
    return 0 unless @$first == @$second;
    
    for (my $i = 0; $i < @$first; $i++) {
        return 0 if $first->[$i] ne $second->[$i];
    }
    return 1;
}

Source: perldoc -q "How do I test whether two arrays"