On 3/16/2011 10:49 AM, Brian Fraser wrote:
Assuming you are using strict and warnings,
Use quotemeta or \Q\E[0] instead of trying to escape things manually... Your
sanity will thank you.
And yes, the \D* could be troublesome; it depends on the text you are
matching against! For instance, 1.2.3.4.5 is not a valid IP, but you'd match
and replace part of it anyway. There's a great section about this on
Mastering Regular Expressions[1], "5.2.2. Matching an IP Address" and
"5.2.2.1. Know your context".
my $old_ip_address = "1.2.3.4";
my $new_ip_address = "5.6.7.8"
$read_line =~ s/
(?<![\w.]) #No alphanumeric or
period before the IP
\Q$old_ip_address_regexp\E #Quotemeta instead of trying to do
things by hand
(?![\w.]) #No alphanumeric or
period after the IP
/$new_ip_address/xg; #No need for $1 and $2, as we don't capture
anything.
Brian.
[0] http://perldoc.perl.org/functions/quotemeta.html
[1] http://regex.info/
It's possible there could be an alphabet character before the ip address
as in:
-s1.2.3.4
So given that possibility, would this be correct:
$read_line =~
s/(?<![\d.])\Q$old_ip_address_regexp\E(?![\d.])/$new_ip_address/g;
Can you explain:
?<!
?!
I was trying to find explanations of them, but they are difficult to
search on.
What is the purpose of the 'x' modifier assuming that is with regard to
ignoring whitespace. Was that included because of the format in which
you provided your example... broken across lines and additional whitespace?
I chose to drop it in my rewrite assuming that is true.
Thanks,
Jim
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/