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

What I would like to achieve is the following:
my $regex = "foo"; #any pattern, few characters here for simplicity my $string = "this is a foo"; $string =~ s/$regex/'bar'/ge; print $string;
and the output would be 'this is a bar'

When i do this though, it tells me that I have not yet declared $regex.

Replies are listed 'Best First'.
Re: $variable as regex in s///
by liverpole (Monsignor) on Jul 20, 2006 at 19:33 UTC
    As philcrow says, this works for me too.

    But I wanted to point out something else ...

    Is there a good reason that you're using the "evaluate" flag? (the e of ge)  Because, if not, you may just have wanted:

    $string =~ s/$regex/'bar'/g; # This will print ... "this is a 'bar'" # but with "/ge" .... "this is a bar"

    It took me a moment to figure out why the output didn't contain apostrophes!


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: $variable as regex in s///
by philcrow (Priest) on Jul 20, 2006 at 19:20 UTC
    Your code worked for me. Maybe there was a typo in the version you actually ran?

    Phil