Skip to Content
Perl语言入门(第8版)
book

Perl语言入门(第8版)

by Randal L. Schwartz, brian d foy, Tom Phoenix
October 2022
Beginner to intermediate
390 pages
7h 5m
Chinese
Southeast University Press
Content preview from Perl语言入门(第8版)
76
4
子程序中的私有变量
既然每次调用子程序时
Perl
都会给我们新的
@_
,难道不能利用它构造私有变量吗?
答案当然是可以。
默认情况下
Perl
里的所有变量都是全局变量,也就是说,在程序里的任何地方都可
以访问它们。但你随时可以借助
my
操作符来创建私有变量,我们称之为词法变量
lexical variable
):
sub max {
my($m, $n); #
该语句块中的新私有变量
($m, $n) = @_; #
将参数赋值给变量
if ($m > $n) { $m } else { $n }
}
这些变量属于封闭语句块中的私有变量(或者也可以称作有限作用域(
scoped
)变
量),语句块之外任意地方的
$m
$n
都完全不受这两个私有变量的影响。反过来
也是,外部变量同样无法影响内部的私有变量,存心也好意外也罢,两不相犯。所
以,我们可以把这个子程序放进世界上任何一个
Perl
程序里,不用担心它和哪个程
序中可能存在的同名
$m
$n
变量冲突。当然,如果那个程序中碰巧也有个子程序
&max
,那就乱了。
另外值得一提的是,在前一个例子的
if
语句块中,作为返回值的表达式后面没有分
号。分号实际上是一个语句分隔符,而不是语句结束符。虽然
Perl
允许你省略语句块
中最后一个分号,但实际上通常只有像前面的例子那样,代码简单到整个语句块内只
有一行时,才可以省略分号。
前一个例子中的子程序还可以进一步简化。你是否注意到列表
($m, $n)
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

Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉
Perl语言入门

Perl语言入门

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 9787576602036