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版)
文件测试
227
但如果省略参数,请特别小心,任何接在文件测试操作符之后的,就算看起来不像,
也会被当作要测试的目标。比方说,你想知道以千字节为单位(而不是以字节为单
位)的文件大小,那么你可能会直接把
-s
测试的结果除以
1000
(或是
1024
),像这
样:
#
文件名保存在
$_
my $size_in_K = -s / 1000; #
糟糕!
Perl
的语法解析器看到斜线时,不会认为那是一个除法操作符。因为它在看
-s
操作符后,就要尝试寻找它的可选操作数,也就是要测试的文件,现在它看到
的是一个以斜线开头的,像是某个正则表达式,但却找不到结尾,于是报错。要避免
这种问题,可在文件测试操作符的两边加上括号:
my $size_in_k = (-s) / 1024; #
默认用
$_
测试
当然,明确写上要测试的文件总是安全稳妥的做法:
my $size_in_k = (-s $filename) / 1024;
同一文件的多项属性测试
如果要一次测试某个文件的若干属性,可以将各个文件测试组成一个逻辑表达式。比
如我们只想操作那些既可读又可写的文件,可以依此检查这两个属性并用
and
合并起
来:
if (-r $filename and -w $filename) {
... }
这可是个非常耗费资源的操作,每次进行文件测试时,
Perl
都得从文件系统中取出
所有相关信息(实际上,每次
Perl
都在内部做了一次
stat
操作,下节我们就会介
绍)。虽然在做
-r
测试的时候,我们已经拿到了所有相关信息,可到了做 ...
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