例如:
open (PS , " tail -n 1 $file | grep win " );
我想查找文件句柄是否为空。
尽管eof
在您尝试读取它之前调用会产生您在这种特殊情况下所期望的结果,但请注意perlfunc 文档eof
末尾的建议:
你的命令最多会产生一行,所以把它放在一个标量中,例如,
chomp(my $gotwin = `tail -n 1 $file | grep win`);
请注意,退出状态grep
告诉您您的模式是否匹配:
2.3 退出状态
通常,如果找到选定的行,则退出状态为 0,否则为 1 ...</p>
此外,tail
成功时退出 0,失败时退出非零。使用该信息对您有利:
#! /usr/bin/perl
use strict;
use warnings;
my $file = "input.dat";
chomp(my $gotwin = `tail -n 1 $file | grep win`);
my $status = $? >> 8;
if ($status == 1) {
print "$0: no match [$gotwin]\n";
}
elsif ($status == 0) {
print "$0: hit! [$gotwin]\n";
}
else {
die "$0: command pipeline exited $status";
}
例如:
$ > 输入.dat $ ./prog.pl ./prog.pl: 不匹配 [] $回声赢>输入.dat $ ./prog.pl ./prog.pl:命中![赢] $ rm输入.dat $ ./prog.pl 尾巴:无法打开“input.dat”进行阅读:没有这样的文件或目录 ./prog.pl: 不匹配 []
open (PS,"tail -n 1 $file|");
if($l=<PS>)
{print"$l"}
else
{print"$file is empty\n"}
好吧...从头开始...我没有建立关于文件句柄实际上是管道输出的连接。
您应该使用stat来确定文件的大小,但您需要确保首先刷新文件:
#!/usr/bin/perl
my $fh;
open $fh, ">", "foo.txt" or die "cannot open foo.txt - $!\n";
my $size = (stat $fh)[7];
print "size of file is $size\n";
print $fh "Foo";
$size = (stat $fh)[7];
print "size of file is $size\n";
$fh->flush;
$size = (stat $fh)[7];
print "size of file is $size\n";
close $fh;