Search code examples
perlsymbolic-references

Why does Perl evaluate code in ${...} during string interpolation?


Why does the following snippet work at all? And what evil might be possible using this? But seriously, is there any reason, the code in ${} gets evaluated at all and then used as scalar reference?

use strict;
no strict 'refs';

our $message = "Hello world!";
print "${ lc 'MESSAGE' }\n";

Solution

  • It's ok, unless you use symbolic references. Suppose the following code:

    my %messages = (hello => "Hello world!", bye => "Bye-bye, world!");
    sub get_message_ref { return \$messages{$_[0]} }; # returns scalarref
    print "${ get_message_ref('bye') }\n";
    

    Agree, its usefulness is not obvious with scalarrefs, but it is very useful with arrayrefs.

    print "keys: @{[keys %messages]}\n";