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
In reply to Re^2: Bash-style Parameter expansion in Perl? (or)
by tye
in thread Bash-style Parameter expansion in Perl?
by bubnoff
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |