Does Perl have PHP-like dynamic variables?

前端 未结 5 1669
北恋
北恋 2020-12-03 06:16

In PHP, I can write:

$vname = \'phone\';
$$vname = \'555-1234\';
print $phone;

... And the script will output \"555-1234\".

Is ther

5条回答
  •  星月不相逢
    2020-12-03 06:21

    You can't do this with the strict pragma enabled, and the strict pragma should usually always be enabled. You can do it with the pragma off though, take a look at this one liner:

    perl -le 'my $vname = "phone"; ${ $vname } = "555-1234"; print $phone'
    

    That will work, but this will not:

    perl -Mstrict -le 'my $vname = "phone"; ${ $vname } = "555-1234"; print $phone'
    

    "-Mstrict" tells it to "use strict".

    It is almost always better to use a hash for something like this, which is about the same as an associative array in PHP.

提交回复
热议问题