$ program file1 file2 This is a line from the first file. Here is the last line of the first file. -- end of current file -- This is a line from the second and last file. Here is the last line of the last file. --end of current file -- $ 下面把eof改为eof(),第二个程序为:
1: #!/usr/local/bin/perl 2: 3: while ($line = <>) { 4: print ($line); 5: if (eof()) { 6: print ("-- end of output --n"); 7: } 8: } 运行结果如下:
$ program file1 file2 This is a line from the first file. Here is the last line of the first file. This is a line from the second and last file. Here is the last line of the last file. -- end of output --$ 这时,只有所有文件都读过了,eof()才返回真,如果只是多个文件中前几个的末尾,返回值为假,因为还有要读取的输入。 9)间接文件变量 对于上述各函数open, close, print, printf, write, select和eof,都可以用简单变量来代替文件变量,这时,简单变量中所存贮的字符串就被看作文件变量名,下面就是这样一个例子,此例很简单,就不解释了。需要指出的是,函数open, close, write, select和eof还允许用表达式来替代文件变量,表达式的值必须是字符串,被用作文件变量名。
1: #!/usr/local/bin/perl 2: 3: &open_file("INFILE", "", "file1"); 4: &open_file("OUTFILE", ">", "file2"); 5: while ($line = &read_from_file("INFILE")) { 6: &print_to_file("OUTFILE", $line); 7: } 8: 9: sub open_file { 10: local ($filevar, $filemode, $filename) = @_; 11: 12: open ($filevar, $filemode . $filename) || 13: die ("Can't open $filename"); 14: } 15: sub read_from_file { 16: local ($filevar) = @_; 17: 18: <$filevar>; 19: } 20: sub print_to_file { 21: local ($filevar, $line) = @_; 22: 23: print $filevar ($line); 24: } 2、跳过和重读数据