eof函数

本文通过两个示例程序对比了Perl语言中eof与eof()函数的行为差异,特别是当它们用于判断文件读取状态时的不同表现。eof在读到文件末尾时立即返回真值,而eof()则在所有输入文件都被读完后才返回真。
eof函数查看最后一次读文件操作是否为文件最后一个记录,如果是,则返回非零值,如果文件还有内容,返回零。
    一般情况下,对eof的调用不加括号,因为eof和eof()是等效的,但与<>操作符一起使用时,eof和eof()就不同了。现在我们来创建两个文件,分别叫做file1和file2。file1的内容为:
     This is a line from the first file.
     Here is the last line of the first file.
    file2的内容为:
     This is a line from the second and last file.
     Here is the last line of the last file.
    下面就来看一下eof和eof()的区别,第一个程序为:
1: #!/usr/local/bin/perl
2: 
3: while ($line = <>) {
4:   print ($line);
5:   if (eof) {
6:     print ("-- end of current file --\n");
7:   }
8: }
    运行结果如下:
$ 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()才返回真,如果只是多个文件中前几个的末尾,返回值为假,因为还有要读取的输入。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/230160/viewspace-623151/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/230160/viewspace-623151/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值