Perl 有类似 PHP 的动态变量吗? [英] Does Perl have PHP-like dynamic variables?

查看:21
本文介绍了Perl 有类似 PHP 的动态变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中,我可以写:

In PHP, I can write:

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

...脚本将输出555-1234".

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

Perl 中是否有任何等价物?

Is there any equivalent in Perl?

有什么方法可以将 $phone 限制在本地块的范围内,就好像我写了 my $phone 一样?使用 my $$vname 会出现无法在 at ... 中声明标量取消引用"错误.

Is there any way to constrain $phone to the scope of the local block, as if I'd written my $phone? Using my $$vname gives me "Can't declare scalar dereference in my at ..." errors.

推荐答案

您尝试执行的操作称为符号引用".虽然您可以在 Perl 中执行此操作您不应该.符号引用仅适用于全局变量——不适用于词法 (my) 变量.没有办法限制它们的范围.符号引用是危险的.因此,它们在 strict pragma 下不起作用.

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

在少数情况下,symrefs 是有用的,甚至是必要的.例如,Perl 的导出机制使用它们.这些是高级主题.当你准备好迎接他们时,你就不需要问如何了.;-)

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. ;-)

这篇关于Perl 有类似 PHP 的动态变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆