Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior in a perl regexp with global substitution

Tags:

regex

perl

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.

like image 913
rcout Avatar asked May 10 '11 15:05

rcout


2 Answers

First .* matches the a, then it matches the empty string after the a. Maybe you want .+?

like image 182
ysth Avatar answered Oct 18 '22 15:10

ysth


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.

like image 20
Jav_Rock Avatar answered Oct 18 '22 15:10

Jav_Rock