Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

using variables in regular expr replace

by b888 (Beadle)
on Dec 02, 2004 at 17:41 UTC ( #411878=perlquestion: print w/replies, xml ) Need Help??

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

Gretting all.

I trued to use variables in s/// and met following problem: perl interpreter tries to use these variables' values as reg expessions. How can i ommit this?

In general algorythm looks like

my $line = "<a href=\"/{HOST}?action\">123</a>:</b><br>". "[img-smile \"58-41\" \":)\"]"; my $var1 = "<img src=\"1-2.gif\" alt=\"[---]\">"; (my $var2) = $line =~ /(\[img-smile [^]]+\])/; $line =~ s/$var2/$var1/; print $line;

And get Invalid [] range "8-4" in regex; marked by <-- HERE in m/[img-smile "58-4 <-- HERE 1..."

P.S. I can't use ' instead of " because of algorytm specific.

Replies are listed 'Best First'.
Re: using variables in regular expr replace
by Joost (Canon) on Dec 02, 2004 at 17:45 UTC

      And just to elaborate on why you need to do this, remember that [] indicates a character class inside a regular expression (i.e. [a-c] means any of the characters a, b, or c). Your [img ... 8-4 ... ] is being interpreted as a character class, and you've got an invalid range (the character 8 is "bigger" than 4 and hence the correct way to specify the range of characters would be [4-8]).

      At any rate you really should either escape the square brackets or use \Q...\E as shown above (and you should read perldoc perlretut and perldoc perlre).

Re: using variables in regular expr replace
by Eimi Metamorphoumai (Deacon) on Dec 02, 2004 at 17:53 UTC
    Use \Q and \E
    $line =~ s/\Q$var2\E/$var1/;
    (In this case you don't need the \E at the end, since it'll end at the end of the regexp anyway, but it's good to know if you do need it later.)

    Also, I'm not sure what you mean by "I can't use ' instead of " because of algorytm specific", but if you need to interpolate variables and still not have to quote quotes.

    my $line = <<"HTML"; <a href="/{HOST}?action">123</a>:</b><br>[img-smile "58-41" ":)"] HTML chomp $line;
    Or you can use qq with just about any delimiter.
    my $line = qq#<a href="/{HOST}?action">123</a>:</b><br>[img-smile "58- +41" ":)"]#;
      Thanks to all

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://411878]
Approved by Joost
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2021-03-01 05:36 GMT
Find Nodes?
    Voting Booth?

    No recent polls found