12

Is the first and the second substitution equivalent if the replacement is passed in a variable?

#!/usr/bin/env perl6
use v6;

my $foo = 'switch';
my $t1 = my $t2 = my $t3 = my $t4 = 'this has a $foo in it';

my $replace = prompt( ':' ); # $0

$t1.=subst( / ( \$ \w+ ) /, $replace );
$t2.=subst( / ( \$ \w+ ) /, { $replace } );
$t3.=subst( / ( \$ \w+ ) /, { $replace.EVAL } );
$t4.=subst( / ( \$ \w+ ) /, { ( $replace.EVAL ).EVAL } );

say "T1 : $t1";
say "T2 : $t2";
say "T3 : $t3";
say "T4 : $t4";

# T1 : this has a $0 in it
# T2 : this has a $0 in it
# T3 : this has a $foo in it
# T4 : this has a switch in it
jjmerelo
  • 22,578
  • 8
  • 40
  • 86
sid_com
  • 24,137
  • 26
  • 96
  • 187

1 Answers1

9

The only difference between $replace and {$replace} is that the second is a block that returns the value of the variable. It's only adding a level of indirection, but the result is the same. Update: Edited according to @raiph's comments.

jjmerelo
  • 22,578
  • 8
  • 40
  • 86
  • 2
    I'm curious why you wrote "returns the variable itself". I consider it misleading and, having reflected, don't see why you didn't write "returns the value", which is what actually happens. In `my $replace = 99; sub term: () is rw { $replace }; foo = 42; say $replace; # 42` the `$replace` in `{ $replace }` does indeed yield the *variable itself*, not the value, and the block returns the variable itself, not the value it contains. But in the `{ $replace }` in sid's example, the `$replace` yields the *value* of the variable, so the block also returns that *value*, not the variable itself. – raiph Apr 20 '19 at 15:10
  • @raiph that's correct, returns the value; in your example it actually returns a writable container into the variable. I'll change it anyway. – jjmerelo Apr 20 '19 at 15:17
  • 2
    Your edit still reads oddly imo. Why mention "the variable itself" when the variable (container) is irrelevant? It's the exact same as the difference between `42` and `{ 42 }`. "in your example it actually returns a writable container into the variable" They are essentially the same thing in my example. `my $replace = 99; sub term: () is rw { $replace }; say $replace.WHERE == foo.WHERE; # True`. The symbol `$replace` is bound to a new container in the `my`. Then the `is rw` tells P6 to interpret the `$replace` in `{ $replace }` as the container (variable), not the value it holds. – raiph Apr 20 '19 at 16:20