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语言入门
84
4
非标量返回值
子程序不仅可以返回标量值,如果在列表上下文中调用它,它还可以返回列表值。
要判断子程序是在标量上下文还是列表上下文中被调用,可以用
wantarray
数测试,为真时返回列表,为假时返回标量。
假设我们希望取出某段范围的数字(效果如同范围操作符
..
所产生的递增序列)并
按倒序返回。虽然范围操作符只能产生递增序列,但要取得倒序的结果也很简单:
sub list_from_fred_to_barney {
if ($fred < $barney) {
#
$fred
数到
$barney
$fred..$barney;
} else {
#
$fred
倒数回
$barney
reverse $barney..$fred;
}
}
$fred = 11;
$barney = 6;
@c = &list_from_fred_to_barney; # @c
的值为
(11, 10, 9, 8, 7, 6)
此例中,我们会先用范围操作符取得从
6
11
的列表,再用
reverse
操作符把它反
转过来。最后的结果就是我们想要的:
$fred
11
)倒数到
$barney
6
)的列表。
其实你还可以什么都不返回。单写一个
return
不给任何参数时,在标量上下文中的
返回值就是
undef
,在列表上下文中则是空列表。这通常用于表示子程序执行有误,
它告诉调用者无法取得有意义的返回值。
持久化私有变量
在子程序中用
my
操作符可以创建私有变量,但每次调用子程序时,这个私有变量都 ...
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