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

后端 未结 3 934
死守一世寂寞
死守一世寂寞 2021-01-05 09:26

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 al

3条回答
  •  遥遥无期
    2021-01-05 09:38

    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";
    

提交回复
热议问题