【问题标题】:How can I tell if a filehandle is empty in Perl?如何判断 Perl 中的文件句柄是否为空?
【发布时间】:2010-05-10 11:38:21
【问题描述】:

例如:

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

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

【问题讨论】:

  • 你想做什么?你更关心文件是否存在或文件是否为空?
  • 执行后我想知道 PS 是不是空的!

标签: perl filehandle


【解决方案1】:

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

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>;
}

【讨论】:

    【解决方案2】:

    虽然在尝试读取之前调用eof 会产生您期望的结果在这种特殊情况下,但请注意perlfunc documentation on eof 末尾的建议:

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

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

    chomp(my $gotwin = `tail -n 1 $file | grep win`);
    

    请注意,grep 的退出状态会告诉您您的模式是否匹配:

    2.3 退出状态

    通常,如果找到选定的行,则退出状态为 0,否则为 1……

    此外,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";
    }
    

    例如:

    $ > input.dat
    $ ./prog.pl
    ./prog.pl: 不匹配 []
    $回声赢>输入.dat
    $ ./prog.pl
    ./prog.pl:命中! [赢]
    $ rm输入.dat
    $ ./prog.pl
    tail:无法打开“input.dat”进行阅读:没有这样的文件或目录
    ./prog.pl: 不匹配 []

    【讨论】:

      【解决方案3】:
      open (PS,"tail -n 1 $file|");
      if($l=<PS>)
        {print"$l"}
      else
        {print"$file is empty\n"}
      

      【讨论】:

        【解决方案4】:

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

        您应该使用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;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-03-15
          • 2015-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多