On Sep 24, 2005, at 5:27, Ling F. Zhang wrote:
regren.pl "REGEXP1" "REGEXP2"
Note that the second one is not a regexp as the script uses it.
would do
$ARG1 = shift @ARGV;
$ARG2 = shift @ARGV;
// some code to obtain a filename list and loop:
$filename =~ s/$ARG1/$ARG2/
and rename the file accordingly...
but when I do:
regren.pl "^(.*?)\.ext" "$1"
Perl replace the matched string with string literal
'$1' not the first matched part as what $1 should be.
This is probably pretty dump, but any idea?
Yes.
Imagine $x is the string "foo". When you interpolate $x in a string
you know "foo" ends up there:
print "hey, $x";
prints
hey, foo
Now, if $x is the string '$1', by the same rule the output would be
hey, $1
Perl stops after variables have been interpolated once, it does not
recurse.
That's exactly what is happening in your example: $ARGV2 is the
string '$1' and it is interpolated in
$filename =~ s/$ARG1/$ARG2/
so in the replacement part we get a literal '$1' that is _not_
further interpreted as the variable $1. Hence, that '$1' ends up in
$filename as is.
Once that is understood, the workaround is to tell Perl you want to
interpolate *and* to evaluate the resulting string. To accomplish
that we have the double /ee. The first /e says you want $ARGV2 to be
evaluated. Since $ARGV2 is a scalar it evaluates to the string '$1',
so far the same we get with interpolation. Now, the second /e forces
evaluation of '$1' itself, which is what we want.
For that rename utility you are playing with there's a gotcha. For
instance if all you wanted was to move "foo.pl" to "bar.pl" then
s/$ARGV1/$ARGV2/ee
wouldn't work, try it.
The reason is that "bar.pl" would be interpreted, due to the double /
ee, and that means the concatenation of the bareword "bar" with the
bareword "pl". Quite different from the innocent mv we wanted to
emulate. You could fix that letting the user say he wants /ee or not
with some flag of the utility, for example.
-- fxn
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>