您的位置:首页 >> Web开发 >> CGI技术 >> 正文
CGI技术 RSS
 

Perl/Tk FAQ - 12.4 变量必须申明为“my”吗?

http://www.rdxx.com 07年11月30日 23:11 我要投稿

关键词: 变量 , FAQ , Perl

  原文:

12.4. Must I use "my" on all my variables?

If you use strict; (as recommended) the answer is "probably". This confines the variables names to your namespace - so your variable does not conflict with one in the module(s) your are using (you are at the least useing Tk;). my does "lexical scoping" on a variable rather than the "dynamic scoping" done by local (like auto variables in C). The difference between these two is that the scope of my $var is confined to the block (sub, if, foreach, etc.) in which it is declared and used, as opposedto local $iable which can propogate to all blocks called by the block in which it is declared. In general the confined scope of my $var means that its use will proceed quicker and more efficiently than local $iable.

If you give a fully qualified variable name such as $main::var = 1; # No "my" needed

Then no my $var is needed. However, the lexical scoping of my $var makes it preferable.

If you choose to use my (as recommended) then beware that you should declare a variable my only at the first use (instantiation) of a variable. Consider yet another way to re-write the "Hello World!" script: #!/usr/local/bin/perl -w use strict; use Tk; my $main = new MainWindow; my $label = $main->Label(-text => 'Hello World!'); my $button = $main->Button(-text => 'Quit', -command => sub{exit}); $label->pack; #no "my" necessary here $button->pack; #or here MainLoop;

Considering the finite number of names (in particular the high probability that a variable named $label or $button was used in one or more of the extensions to perl that you may be using) it helps one's programming to use strict; and declare variables yours alone with my.

James M. Stern points out that redundant my declarations are not simply useless they can be dangerous as in the following script which will not work: #!/usr/local/bin/perl -w use strict; use Tk; my $main = new MainWindow; my $label = $main->Label(-text => 'Hello World!'); my $main; #WRONG: this $main overrides previous my $button = $main->Button(-text => 'Quit', #will now fail -command => sub{exit}); $label->pack; $button->pack; MainLoop;



译文:

12.4 变量必须申明为“my”吗?



如果你使用了use strict;(推荐使用),答案是“也许应该”。因为这样就把你的变量名限定在你的脚本的名字空间中,这样你定义的变量就不会和你所使用的模块(你至少使用了Tk模块吧!)中的同名变量冲突了。my定义的变量是“词法范围”,而不同于local所定义的是“动态范围”(就像C语言中的自动变量?)。这两者之间的区别在于,my所定义的变量范围是它所在的程序块(例如,子程序,if,foreach等等);而local所定义的变量的范围则可以延伸到所有在其所定义的程序块中被调用的程序中去。一般说来,my $var所限制的变量范围意味着它比local $iable更快捷和高效。



如果你给出了完整的变量名,例如:

$main::var = 1; #不需要“my”

那么就不需要使用my $var。但是,my $var所定义的词法作用域使它具有更大的优势。



如果你选择使用my申明变量(建议大家使用),那么你必须注意只能在此变量第一次使用的时候(即初始化)对它进行申明。下面,我们考虑用另一种方法来重写“

共2页  1 2


 
 
标签: 变量 , FAQ , Perl 打印本文
 
 
  热点搜索
 
 
 



Valid XHTML 1.0 Transitional
Copyright ©2005 - 2008 Rdxx.Com,All Rights Reserved
收藏本页
收藏本站