问题描述
我正在查看 Perl Monks 上的一些旧 Perl 代码,以找出使用Win32::OLE 和 MS Word.分散在整个代码中的是变量名,如 $MS::Word 等,声明中没有包含my".在 Google 上阅读了一些内容后,我了解到这些被称为包变量"与使用 my 声明的词法变量".
I'm looking at some older Perl code on Perl Monks to figure out programming with Win32::OLE and MS Word. Scattered throughout the code are variables with names like $MS::Word and the like, without a 'my' included in their declaration. After reading a bit on Google, I understand that these are called 'package variables' versus 'lexical variables' declared using my.
我的第一个问题是包变量有什么用?".我(认为)我了解词法变量是什么,但我不明白包变量的用途或它们的用法与词法有何不同,所以我的第二个问题是,'词法变量和包变量有什么区别?'
My first question is 'What are package variables good for?'. I (think) I understand what lexical variables are, but I don't understand the purpose of package variables or how their use differs from lexicals, so my second question would be, 'What is the difference between lexical and package variables?'
推荐答案
包变量存在于符号表中,因此根据其名称,可以从任何其他包或作用域读取或修改它.词法变量的范围由程序文本决定.通过 my() 的私有变量"部分perlsub 联机帮助页提供了有关定义词法的更多详细信息.
A package variable lives in a symbol table, so given its name, it's possible to read or modify it from any other package or scope. A lexical variable's scope is determined by the program text. The section "Private Variables via my()" in the perlsub manpage gives more detail about defining lexicals.
假设我们有以下 MyModule.pm
:
package MyModule;
# these are package variables
our $Name;
$MyModule::calls = "I do not think it means what you think it means.";
# this is a lexical variable
my $calls = 0;
sub say_hello {
++$calls;
print "Hello, $Name!\n";
}
sub num_greetings {
$calls;
}
1;
注意它包含一个包 $calls
和一个词法 $calls
.任何人都可以访问前者,但模块控制对后者的访问:
Notice that it contains a package $calls
and a lexical $calls
. Anyone can get to the former, but the module controls access to the latter:
#! /usr/bin/perl
use warnings;
use strict;
use MyModule;
foreach my $name (qw/ Larry Curly Moe Shemp /) {
$MyModule::Name = $name;
MyModule::say_hello;
}
print MyModule::num_greetings, "\n";
print "calls = $MyModule::calls\n";
程序的输出是
Hello, Larry!
Hello, Curly!
Hello, Moe!
Hello, Shemp!
4
calls = I do not think it means what you think it means.
如您所见,包变量是全局变量,因此所有常见的问题和建议都适用.除非明确提供访问权限,否则 MyModule 包之外的代码不可能访问其词法 $calls
.
As you can see, package variables are globals, so all the usual gotchas and advice against apply. Unless explicitly provided access, it's impossible for code outside the MyModule package to access its lexical $calls
.
经验法则是您几乎总是想使用词法.Perl 最佳实践 by Damian Conway 很直接:永远不要让模块接口的变量部分"(强调原文).
The rule of thumb is you very nearly always want to use lexicals. Perl Best Practices by Damian Conway is direct: "Never make variables part of a module's interface" (emphasis in original).
这篇关于什么时候应该使用包变量和词法变量(有什么区别)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!