Substitute: replacement evaluation
Asked Answered
S

1

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
Scapegrace answered 20/4, 2019 at 6:46 Comment(0)
U
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.

Unbroken answered 20/4, 2019 at 9:50 Comment(3)
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:<foo> () 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.Yehudi
@Yehudi that's correct, returns the value; in your example it actually returns a writable container into the variable. I'll change it anyway.Unbroken
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:<foo> () 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.Yehudi

© 2022 - 2024 — McMap. All rights reserved.