Reputation: 25117
When I want to stringify a variable: does it make a difference whether I put the variable in double quotation marks
$string = "$v";
or whether I concatenate the variable with an empty string
$string = '' . $v;
?
Upvotes: 2
Views: 542
Reputation: 385789
When I want to stringify a variable
So never? Operators that expect a string will stringify their operands. It's super rare that one needs to stringify explicitly. I think I've only ever done this once.
does it make a difference whether I put the variable in double quotation marks
The code generated code is different.
$ perl -MO=Concise,-exec -e'"$v"'
...
3 <#> gvsv[*v] s
4 <@> stringify[t2] vK/1
...
$ perl -MO=Concise,-exec -e'"".$v'
...
3 <$> const[PV ""] s
4 <#> gvsv[*v] s
5 <2> concat[t2] vK/2
...
This difference will matter for objects with overloaded operators, which is one of the few times you might want to explicitly stringify.
$ perl -e'
use overload
q{""} => sub { print "stringified\n"; "" },
"." => sub { print "concatenated\n"; "" };
$v = bless({});
"$v";
"".$v;
'
stringified
concatenated
It will still end up being the same for most classes. You should only have problems with a class for which .
doesn't mean concatenation.
Upvotes: 8