Does Perl have PHP-like dynamic variables?

前端 未结 5 1666
北恋
北恋 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:27

    What you're attempting to do is called a "symbolic reference." While you can do this in Perl you shouldn't. Symbolic references only work with global variables -- not lexical (my) ones. There is no way to restrict their scope. Symbolic references are dangerous. For that reason they don't work under the strict pragma.

    In general, whenever you think you need symbolic references you should use a hash instead:

    my %hash;
    $hash{phone} = '555-1234';
    print $hash{phone};
    

    There are a few cases where symrefs are useful and even necessary. For example, Perl's export mechanism uses them. These are advanced topics. By the time you're ready for them you won't need to ask how. ;-)

提交回复
热议问题