Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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.

Comment on using variables in regular expr replace
Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (14)
As of 2014-07-22 11:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (110 votes), past polls