Skip to Content
Perl语言入门
book

Perl语言入门

by Randal L. Schwartz, brian d foy, Tom Phoenix
August 2018
Beginner to intermediate
382 pages
7h 14m
Chinese
Southeast University Press
Content preview from Perl语言入门
子程序
79
my
声明的词法变量
词法变量可用在任何语句块内,并不仅限于子程序的语句块。例如,在
if
while
foreach
的语句块内都可使用词法变量:
foreach (1..10) {
my($square) = $_ * $_; #
在此循环内的私有变量
print "$_ squared is $square.\n";
}
上例中,变量
$square
对其所属语句块,也就是
foreach
循环的语句块来说是私有
的。如果变量的定义并未出现在任何语句块里,则该变量对于整个程序源文件来说是
私有的。
目前为止,你的程序还用不到两个以上的程序源文件,所以这还不成问题。这里的重
点在于,词法变量的作用域
scope
受限于定义它的最内层语句块内,或文件内。只有
语句块内的代码才能使用这个
$square
变量。
这为程序维护提供了便利:如果
$square
的值出错了,那就可以在有限的代码范围内
找原因。有经验的程序员通过实践,往往倾向于将变量作用域局限在一页或少数几行
代码内,以加快开发和测试周期。
一个程序文件也是一个独立的作用域,所以其中的词法变量到了其他文件是无法访问
的。这里涉及可重用库和模块,我们暂时不讨论,可参考《
Intermediate Perl
》一书。
还需要注意的是,
my
操作符并不会更改变量赋值时的上下文:
my($num) = @_; #
列表上下文
,
($num) = @_;
相同
my $num = @_; #
标量上下文
,
$num ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

计算机科学导论:跨学科方法

计算机科学导论:跨学科方法

罗伯特 塞奇威克, 凯文 韦恩
Perl语言入门(第8版)

Perl语言入门(第8版)

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 9787564177911