jueves, 5 de noviembre de 2009

practical Perl 5 match operator

Here I am again, with some reminders about a few practical things I (and maybe you) should have in mind when doing pattern matching in perl. I'll mainly talk about retrieving results in matches, and the context things.

So I won't talk about the pattern part.

The match operator is called with the m/OHAI/ pattern, or just /OHAI/ . if you don't specify something to match against, perl will use our good friend $_ , so when you iterate through a file, you are probably ok with this convention:


my $yay;
while(<>){
$yay = $_ if /say/ ;
}
print $yay;



Sometimes we don't want to match against $_, and we'd like to parse another var. That's ok, we use the =~ operator, which tells 'm' the variable to do the match with. But there is where I get somewhat puzzled sometimes, because if I want to assign the match to a var, you have to chain it

$match = $string =~ /yay/;

And that doesn't do what we usually want.

I've written this little test script to help me remember how to do proper matchings, and get the info I want from them.