Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace without storing variable

Tags:

regex

perl

Is there a way to do this in one line?

my $b = &fetch();
$b =~ s/find/replace/g;
&job($b)
like image 828
700 Software Avatar asked Jan 29 '26 06:01

700 Software


2 Answers

Sure, with a do {} block:

use strict;
use warnings;

sub fetch { 'please find me' }
sub job   { print @_, "\n"   }

job( do { $_ = fetch(); s/find/replace/g; $_ } );

The reason being that in Perl you cannot do fetch() =~ s/find/replace/;:
Can't modify non-lvalue subroutine call in substitution (s///) at ...

Perl 5.14 will introduce the /r flag (which makes the regex return the string with substitutions rather than the number of substitutions) and will reduce the above to:

job( do { $_ = fetch(); s/find/replace/gr; } );

edited thanks to FM: can shorten the above to:

job( map { s/find/replace/g; $_ } fetch() );

And once Perl 5.14 will be out it can be shortened to:

job( map { s/find/replace/gr } fetch() );
like image 182
mfontani Avatar answered Jan 31 '26 21:01

mfontani


If you are asking whether you have to go through a scalar variable to do the replace, the answer is yes. This is because the result of the substitution has to be stored somewhere. Also, the substitution does not return the variable used, it returns the number of substitutions made. Therefore, you can't inline it (i.e., &job($b =~ s/find/replace/g) ) in the function call.

like image 22
Michael Goldshteyn Avatar answered Jan 31 '26 23:01

Michael Goldshteyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!