Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
Think about Loose Coupling
 
PerlMonks  

using variables in regular expr replace

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

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

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 12: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 12: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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://411878]
Approved by Joost
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.