How should I stringify a variable?

515 views Asked by At

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;

?

1

There are 1 answers

3
ikegami On BEST ANSWER

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.