| |
|
| |
 |
|
perl教学 第十一篇 文件系统之三
|
|
| 日期:2005-7-18 8:46:04 来源:易特网络技术 编辑:黑鹰 点击: |
运行结果如下:
$ 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写操作之前跳过的字节数。
|
上一篇:perl教学 第十一篇 文件系统之四
下一篇:perl教学 第十一篇 文件系统之二
[发送给好友] [打印本页] [关闭窗口] [返回顶部] 转载请注明来源:http://www.iyit.net |
|
| 特别声明: 本站除部分特别声明禁止转载的专稿外的其他文章可以自由转载,但请务必注明出处和原始作者。文章版权归文章原始作者所有。对于被本站转载文章的个人和网站,我们表示深深的谢意。如果本站转载的文章有版权问题请联系编辑人员,我们尽快予以更正。 |
| 责任编辑: 黑鹰 |
投稿作者: 易特网络 |
| 信息来源: 易特网络技术 |
录入时间: 2005-7-18 8:46:04 |
| 浏览次数: |
投稿信箱: shtghy@163.com |
|
|
|
|