On Mar 28, Bryan R Harris said:
>Why does this segment not work properly?
You would know if you had warnings turned on.
perl -we '$match = "cat(\d+)"'
yields the warning
Unrecognized escape \d passed through at -e line 1.
>$match = "cat(\d+)";
>$replace = "\1dog";
>$_ = "cat15";
>s/$match/$replace/g;
>print $_; # prints --> \1dog
Nope, that prints cat15. Why? Because "cat(\d+)" is the same as
"cat(d+)" because "\d" becomes "d". If you had used single quotes, you
would have been ok. And $replace the string "_dog", where that _
represents an unprintable character -- specifically, character 1 (SOH).
If you had done:
$match = 'cat(\d+)';
$replace = '\1dog';
$_ = "cat15";
s/$match/$replace/;
print;
You would get CLOSER, but not entirely there. $match would be correct,
but you would get \1dog instead of 15dog.
To fix that requires a bit of work. Here are two solutions:
$match = 'cat(\d+)';
$replace = '$1dog'; # XXX: you should not use \1 on the right-hand
# side of a regex; you should use $1
$_ = "cat15";
s/$match/qq(qq($replace))/ee; # qq() is just a fancy "..."
print;
What does THAT do? Well, first, each /e modifier means "execute the
right-hand side as code". Since there are two /e's, we'll be executing it
TWICE. The first time, qq(qq($replace)) returns the text qq($1dog). When
we execute that, we get "15dog".
The other way might be easier to understand:
$match = 'cat(\d+)';
$replace = sub { "$1dog" };
$_ = "cat15";
s/$match/$replace->()/e;
print;
This uses a function reference stored in $replace. What this does is
delay the evaluation of $1 until it's needed.
--
Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/
RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
[ I'm looking for programming work. If you like my work, let me know. ]
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]