为什么Perl的foreach要求它的变量被声明为我的?
今天,我偶然发现Perl中的某些东西,我没有意识到:它将本地化??列表的元素分配给变量.
这当然是在Perl文档中记录的 – 但是我没有记住或读取它. 以下脚本演示了我的意思: use warnings; use strict; my $g = 99; foreach $g (1..5) { p($g); } sub p { my $l = shift; printf ("%2d %2dn",$g,$l); } 脚本打印 99 1 99 2 99 3 99 4 99 5 因为$g被“本地化”到foreach循环. 据我所知,如果我在foreach循环中添加了$g: foreach my $g (1..5) { 实际上,我最终做到这一点,因为我觉得它使得变量在循环中是局部的. 我现在的问题是:有没有一个我使用我的功能会发生变化的情况(假设$g已经在全球宣布). 解决方法
被调查的行为记录在
Foreach Loops in perlsyn年
继续解释
因此,将本地化与本人或离开之间应该没有区别. 有点好奇心
所有这一切从Private Variables via
由于在这两种情况下都创建了一个新的词汇,所以不会有任何实际的区别. 我绝对支持并建议把我放在那里. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |