http://www.perlmonks.org?node_id=1013727


in reply to Replace In a Single Line

In recent versions of Perl, you can do:

$var1 = ($var =~ s/oo//gir);

In pretty much any version of Perl, you can do:

($var1 = $var) =~ s/oo//gi;

Update: the second method is about 35% faster according to my benchmarking. The first one is sometimes more elegant - especially when the variable you're operating on (and don't want to be changed) is $_ such as this map block:

my @without_oo = map { s/oo//rig } @with_oo; # traditional version: my @without_oo = map { (my $x = $_) =~ s/oo//ig; $x } @with_oo;

But in your original example, neither of the two solutions I presented above seems more elegant than the other, so I'd prefer the faster one.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'