print "fred is '$fred', barney is '$barney'\n" if $I_am_curious;
用这种“倒装句”编写程序可以把语句中重要的部分放在前面。上面那条语句的重
点是查看一些变量的值,而不是检查你是否好奇。当然,
$I_am_curious
这个变量是
我们杜撰出来的,并非内置的
Perl
变量。通常使用这个技巧的时候,变量会被命名
为
$TRACING
,或者用
constant
编译指令来声明一个全局常量。有些人喜欢将整个语
句写成一行,也可能在
if
之前加上些制表符使它向右边缩进一些,上面那个例子就
是如此。也有人喜欢将
if
修饰符放在下一行并缩进一段距离:
print "fred is '$fred', barney is '$barney'\n"
if $I_am_curious;
虽然这些带有修饰符的表达式都可以用块的形式重写,即用最传统的方法写,但反过
来,由传统写法往带有修饰符的写法改写却未必可以。修饰符的两边都只能写单个表
达式,因此不能写某事
if
某事
while
某事
until
某事
unless
某事
foreach
某事,因
为那样太让人困惑了。另外修饰符的左边也不能放多条语句。如果确实需要,还是建
议你回到传统写法,仍然写那些圆括号和花括号。
如同我们之前在
if
修饰符部分谈到的,右边的控制表达式总是先求值,和传统写法
的执行顺序是一样的。
在使用
foreach
修饰符的时候无法自选控制变量,必须使用 ...
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.
O’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
I 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
I’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
I'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.