in reply to Mathching an array in regex

That won't work like that. To see what's happening, try

perl -MO=Deparse test.pl

on the code put in test.pl. For
#!/usr/bin/perl use strict; use warnings; my @arr=('cool','guy','here'); my $str1="I am cool"; if($str1 =~ m/@arr/){ print "Matched"; }
this will show you
$ perl -MO=Deparse test.pl use warnings; use strict 'refs'; my(@arr) = ('cool', 'guy', 'here'); my $str1 = 'I am cool'; if ($str1 =~ /@arr/) { print 'Matched'; } test.pl syntax OK
Note that /@arr/ is taken literally - it so has to be, only scalars are interpolated inside regexes, not arrays. You might try something like
#!/usr/bin/perl use strict; use warnings; my @arr=('cool','guy','here'); my $joined_rx = join( '|', map { quotemeta($_) } @arr ); my $str1="I am cool"; if ($str1 =~ m/$joined_rx/) { print "Matched"; }
but I'd prefere the solution with a loop/map based on the given array.

Hth.

Update: ikegami is right, of course. @ _is_ expanded in regexes too - but the extra spaces it introduces makes the resulting rx something that's far away from what was intended. My bad, sorry.

Replies are listed 'Best First'.
Re^2: Mathching an array in regex
by narainhere (Monk) on Oct 12, 2007 at 12:21 UTC
    Thanks for introducing me to perl -MO utility, can you direct me to the documentation on that, I don't find it in perldoc:perl -MO=Deparse test.pl.I disagree with you on the point that @arr is not expanded, the following code produces Matched as o/p (Note the $str1 value and array)
    #!/usr/bin/perl use strict; use warnings; my @arr=('cool','guy','here'); my $str1="cool guy here"; if($str1 =~ m/@arr/){ print "Matched"; }

    The world is so big for any individual to conquer

      Look for B::Deparse for the docs. The module is unvaluable sometimes

      To the @ expansion in regexes: you're right, of course. I think I just never have tried it, and so I had an 'explanation' at hand.
      Sorry.