0

例如:

open (PS , " tail -n 1 $file | grep win " );

我想查找文件句柄是否为空。

4

4 回答 4

5

您还可以使用eof来检查文件句柄是否已用尽。这是一个松散地基于您的代码的插图。还要注意使用具有 3-arg 形式的词法文件句柄open

use strict;
use warnings;

my ($file_name, $find, $n) = @ARGV;

open my $fh, '-|', "tail -n $n $file_name | grep $find" or die $!;

if (eof $fh){
    print "No lines\n";
}
else {
    print <$fh>;
}
于 2010-05-10T12:10:21.937 回答
3

尽管eof在您尝试读取它之前调用会产生您在这种特殊情况下所期望的结果,但请注意perlfunc 文档eof末尾的建议:

实用提示:您几乎不需要eof在 Perl 中使用,因为输入运算符通常undef在数据用完或出现错误时返回。

你的命令最多会产生一行,所以把它放在一个标量中,例如

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: 不匹配 []
于 2010-05-10T15:01:27.840 回答
1
open (PS,"tail -n 1 $file|");
if($l=<PS>)
  {print"$l"}
else
  {print"$file is empty\n"}
于 2010-05-10T11:59:36.487 回答
-1

好吧...从头开始...我没有建立关于文件句柄实际上是管道输出的连接。

您应该使用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;
于 2010-05-10T13:02:21.003 回答