运行结果如下:
$ 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、跳过和重读数据
函数名 seek
调用语法 seek (filevar, distance, relative_to);
解说 在文件中向前/后移动,有三个参数:
1、filevar,文件变量
2、distance,移动的字节数,正数向前移动,负数往回移动
3、reletive_to,值可为0、1或2。为0时,从文件头开始移动,为1时,相对于当前位置(将要读的下一行)移动,为2时,相对于文件末尾移动。
运行成功返回真(非零值),失败则返回零,常与tell函数合用。
函数名 tell
调用语法 tell (filevar);
解说 返回从文件头到当前位置的距离。
注意:
1、seek和tell不能用于指向管道的文件变量。
2、seek和tell中文件变量参数可使用表达式。
3、系统读写函数
函数名 read
调用语法 read (filevar, result, length, skipval);
解说 read函数设计得与unix的fread函数等效,可以读取任意长度的字符(字节)存入一个简单变量。其参数有四个:
1、filevar:文件变量
2、result:存贮结果的简单变量(或数组元素)
3、length:读取的字节数
4、skipval:可选项,指定读文件之前跳过的字节数。
返回值为实际读取的字节数,如果已到了文件末尾,则返回零,如果出错,则返回空串。
函数名 sysread
调用语法 sysread (filevar, result, length, skipval);
解说 更快的读取数据,与unix函数read等效,参数与read相同。
函数名 syswrite
调用语法 syswrite (filevar, data, length, skipval);
解说 更快的写入数据,与unix函数write等效,参数:
1、filevar:将要写入的文件
2、data:存贮要写入数据的变量
3、length:要写入的字节数
4、skipval写操作之前跳过的字节数。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器