bubnoff has asked for the wisdom of the Perl Monks concerning the following question:

I can do this in bash:
var="hello world" var2=${var/world/earth} echo $var2
Which produces:
hello earth
Is there a similar shortcut in Perl? ...or must I:
my $sentence = qq(Hello World); my $sub2 = $sentence; $sub2 =~ s/World/Earth/; print "$sub2";
Thanks for reading ~ Bubnoff

Replies are listed 'Best First'.
Re: Bash-style Parameter expansion in Perl?
by ikegami (Patriarch) on Jul 08, 2010 at 01:19 UTC
    var="hello world" my $var = "hello world"; var2=${var/world/earth} ( my $var2 = $var ) =~ s/world/earth/; echo $var2 say $var2;
    I believe 5.14 will also allow
    my $var2 = $var =~ s/world/earth/f;
      The new modifier is written /r.

      It is nice to localize the temporary. Sometimes it is also nice to not name the temporary.

      In the following, the small trick is...

      my $var= "hello, world"; for( @{[ $var ]} ) { # Make a copy s/world/earth/; say; # hello, earth } say $var; # hello, world

      ...making $_ not be an alias to $var so $var doesn't get modified. Perl 6 gives one explicit control over such (iterate over read-only aliases, read/write aliases, or read/write copies). Perl 5 requires less explicitly targeted techniques. There are other alternatives to @{[ ... ]}, of course.

      I don't like the implicit scope that makes this work:

      use strict; my $var= "Hello, World!"; for( my $copy= $var ) { s/World/Earth/; print $_, $/; } print $var, $/; eval 'print $copy, $/; 1' or print '$copy no longer in scope', $/; __END__ Hello, Earth! Hello, World! $copy no longer in scope

      but the implicit scope block is there and the above technique may be clearer (less idiomatic).

      - tye        

      Thanks ~ This is what I was looking for. Bubnoff