一、打开、关闭文件
语法为open (filevar, filename),其中filevar为文件句柄,或者说是程序中用来代表某文件的代号,filename为文件名,其路径可为相对路径,亦可为绝对路径。
open(FILE1,"file1");
open(FILE1, "/u/jqpublic/file1");
打开文件时必须决定访问模式,在PERL中有三种访问模式:读、写和添加。后两种模式的区别在于写模式将原文件覆盖,原有内容丢失,形式为:open(outfile,">outfile");而添加模式则在原文件的末尾处继续添加内容,形式为:open(appendfile, ">>appendfile")。要注意的是,不能对文件同时进行读和写/添加操作。
open的返回值用来确定打开文件的操作是否成功,当其成功时返回非零值,失败时返回零,因此可以如下判断:
if (open(MYFILE, "myfile")) {
# here's what to do if the file opened successfully
}
当文件打开失败时结束程序:
unless (open (MYFILE, "file1")) {
die ("cannot open input file file1\n");
}
亦可用逻辑或操作符表示如下:
open (MYFILE, "file1") || die ("Could not open file");
当文件操作完毕后,用close(MYFILE); 关闭文件。
二、读文件
语句$line = <MYFILE>;从文件中读取一行数据存储到简单变量$line中并把文件指针向后移动一行。<STDIN>为标准输入文件,通常为键盘输入,不需要打开。
语句@array = <MYFILE>;把文件的全部内容读入数组@array,文件的每一行(含回车符)为@array的一个元素。
三、写文件
形式为:
open(OUTFILE, ">outfile");
print OUTFILE ("Here is an output line.\n");
注:STDOUT、STDERR为标准输出和标准错误文件,通常为屏幕,且不需要打开。
四、判断文件状态
1、文件测试操作符
语法为:-op expr,如:
if (-e "/path/file1") {
print STDERR ("File file1 exists.\n");
}
文件测试操作符
例:
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 files\n");
五、命令行参数
象C一样,PERL也有存储命令行参数的数组@ARGV,可以用来分别处理各个命令行参数;与C不同的是,$ARGV[0]是第一个参数,而不是程序名本身。
$var = $ARGV[0]; # 第一个参数
$numargs = @ARGV; # 参数的个数
PERL中,<>操作符实际上是对数组@ARGV的隐含的引用,其工作原理为:
1、当PERL解释器第一次看到<>时,打开以$ARGV[0]为文件名的文件;
2






