例:
unless (open(INFILE, "infile")) {
die ("Input file infile cannot be opened.n");
}
if (-e "outfile") {
die ("Output file outfile already exists.n");
}
unless (open(OUTFILE, ">outfile")) {
die ("Output file outfile cannot be opened.n");
}
等价于
open(INFILE, "infile") && !(-e "outfile") &&
open(OUTFILE, ">outfile") || die("Cannot open filesn");
四、模式匹配:
1.概念:模式指在字符串中寻找的特定序列的字符,由反斜线包含:/def/即模式def。其用法如结合函数split将字符串用某模式分成多个单词:@array = split(/ /, $line);
2.匹配操作符 =~、!~
=~检验匹配是否成功:$result = $var =~ /abc/;若在该字符串中找到了该模式,则返回非零值,即true,不匹配则返回0,即false。!~则相反。
五、控制结构
(1)、条件判断:if()elseif()else();
(2)、循环:
1、while循环
2、until循环
3、for循环
4、针对列表(数组)每个元素的foreach循环
open(MYFILE,'1.txt');
@arr = <MYFILE>;
foreach $str (@arr){
print $str;
}
5、do循环
6、循环控制:退出循环为last,与C中的break作用相同;执行下一个循环为next,与C中的continue作用相同;PERL特有的一个命令是redo,其含义是重复此次循环,即循环变量不变,回到循环起始点,但要注意,redo命令在do循环中不起作用。
7、传统的goto语句:goto label;
(3)、单行条件
语法为statement keyword condexpr。其中keyword可为if、unless、while或until,如:
print ("This is zero.n") if ($var == 0);
print ("This is zero.n") unless ($var != 0);
print ("Not zero yet.n") while ($var-- > 0);
print ("Not zero yet.n") until ($var-- == 0);
虽然条件判断写在后面,但却是先执行的。
六、子程序
(1)、定义
子程序即执行一个特殊任务的一段分离的代码,它可以使减少重复代码且使程序易读。PERL中,子程序可以出现在程序的任何地方。定义方法为:
sub subroutine{
statements;
}
(2)、调用
调用方法如下:用&调用
&subname;
...
sub subname{
...
}
七、文件系统:与unix紧密相关,参考:http://shouce.jb51.net/perl5/perl11.htm









