Can somone explain me why the output of this small perl script is "foofoo" (and not "foo") ?
#!/usr/bin/perl -w
my $var="a";
$var=~s/.*/foo/g;
print $var."\n";
Without the g option it works as I though it would but why is the global option matching pattern twice ?
In bash output is "foo" as expected
echo "a"|sed -e "s/.*/foo/g"
Any explanation would be appreciated.
First .*
matches the a, then it matches the empty string after the a. Maybe you want .+
?
It is more fun if you try
$var=~s/.*?/foo/g;
You will get
foofoofoo
The ? modifier matches 1 or 0 times. If you remove the g, you will get
fooa
because it will only replace the empty string, the first one it finds. I love perl.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With