Find and replace without saving a variable

Is there a way to do this on a single line?

my $b = &fetch();
$b =~ s/find/replace/g;
&job($b)
+3
source share
3 answers

Of course, with the block do {}:

use strict;
use warnings;

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

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

The reason is 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 present a flag /r(which causes the regular expression to return a string with replacements, rather than the number of substitutions) and reduce the above:

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

edited by FM: can be shortened above:

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

And as soon as Perl 5.14 is released, it can be shortened to:

job( map { s/find/replace/gr } fetch() );
+4
source

, , . , - . , , . , (.. ($ b = ~ s/find/replace/g)) .

+4
for (fetch() . '') {   # append with '' to make sure it is a non-constant value
    s/find/replace/g;
    job($_)
}

or use applyfrom one of the List modules:

use List::Gen qw/apply/;

job( apply {s/find/replace/g} fetch() );
0
source

Source: https://habr.com/ru/post/1771078/


All Articles