pc2 has asked for the wisdom of the Perl Monks concerning the following question:

salutations, is there some way to put the matching pattern (regexp) in a variable? for example:
$var = "([f][o][o]|[b][a][r])"; @ret = grep(/$var/, @foo);
but this /$var/ technique doesn't work. is there some other technique? salutations,

Replies are listed 'Best First'.
Re: set value of a variable to a regexp
by moritz (Cardinal) on Aug 19, 2007 at 09:58 UTC
Re: set value of a variable to a regexp
by FunkyMonk (Bishop) on Aug 19, 2007 at 10:01 UTC
    Your code looks OK, are you sure the problem isn't with what you're trying to match against?

    Try this:

    my $re = 'fo+|zzz'; my @matches = grep /$re/, qw/ f fo foo bar foobar zzzz /; print "@matches";

    Output:

    fo foo foobar zzzz

Re: set value of a variable to a regexp
by codeacrobat (Chaplain) on Aug 19, 2007 at 11:51 UTC
    Maybe what you are looking for is Regexp::Assemble.

    -- snip
    source - When using tracked mode, after a successful match is made, returns the original source pattern that caused the match. In Perl 5.10, the $^R variable can be used to as an index to fetch the correct pattern from the object. If no successful match has been performed, or the object is not in tracked mode, this method returns "undef".
    -- snap
    use Regexp::Assemble; my $r = Regexp::Assemble->new->track(1)->add(qw(foo? bar{2} [Rr]at)); for my $w (qw(this food is rather barren)) { if ($w =~ /$r/) { print "$w matched by ", $r->source($^R), $/; } else { print "$w no match\n"; } }
    prints
    this no match food matched by foo? is no match rather matched by [Rr]at barren matched by bar{2}