Perl是否具有PHP类动态变量? [英] Does Perl have PHP-like dynamic variables?

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

问题描述

在PHP中,我可以写:

  $ vname ='phone'; 
$$ vname ='555-1234';
打印$电话;

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



Perl中是否有任何等价物?



有没有办法限制 $ phone 到本地区域的范围,好像我写了我的$电话?使用我的$$ vname 给我无法在我的...声明标量取消引用错误。

解决方案

你试图做什么叫做符号引用。虽然您可以在Perl 您不应该这样做。符号引用仅适用于全局变量 - 不适用于词法( my )。没有办法限制他们的范围。 符号引用是危险的。因为这个原因,它们不能在 strict pragma下工作。



一般来说,只要您认为需要符号引用,您应该使用哈希值:

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

有些情况下,symrefs是有用的,甚至是必要的。例如,Perl的出口机制使用它们。这些是高级主题。当你准备好他们时,你不需要问如何。 ; - )


In PHP, I can write:

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

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

Is there any equivalent in Perl?

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.

解决方案

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

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

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