[Purdue-pm] smart matching in Perl

Mark Senn mark at purdue.edu
Fri Feb 25 12:29:14 PST 2011


The '~~' is used to do smart matching in Perl.  I like smart match.

I'm working on a program that needs to run on Perl 5.10 and 5.12 (don't
ask).  I'd love to use Perl's smart match to do it but that won't work
in 5.10.  Below is a program to demonstrate two ways of getting an
answer.  I don't claim either of these are optimal.    -mark

#!/usr/local/bin/perl

@re = (
    qr /^a$/,
    qr /^b$/
);

foreach (qw(a c))
{

    # In Perl 5.10 here's one way to print if $_
    # doesn't match any regular expression in @re:

    $t = 0;
    foreach my $re (@re)
    {
        if ($_ =~ $re)
        {
            $t = 1;
            last;
        }
    }

    ($t)  or  print qq/"$_" doesn't match\n/;


    # Get same results in Perl 5.12:

    print qq/"$_" doesn't match\n/ unless ($_ ~~ @re);

}


More information about the Purdue-pm mailing list