代码之家  ›  专栏  ›  技术社区  ›  joe

在Perl中,如何判断文件句柄是否为空?

  •  0
  • joe  · 技术社区  · 15 年前

    例如:

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

    我想知道文件句柄是否为空。

    4 回复  |  直到 15 年前
        1
  •  5
  •   FMc TLP    15 年前

    你也可以使用 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>;
    }
    
        2
  •  3
  •   Greg Bacon    15 年前

    尽管打电话 eof 在试图从中读取结果之前 在这种特殊情况下 ,注意结尾处的建议 perlfunc documentation on eof :

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

    你的命令最多只能产生一行,所以用标量来表示, 例如 ,

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

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

    2.3退出状态

    通常,如果找到所选行,则退出状态为0,否则为1。

    也, tail 成功时退出0,失败时退出非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: no match []
    $ echo win >input.dat
    $ ./prog.pl 
    ./prog.pl: hit! [win]
    $ rm input.dat 
    $ ./prog.pl 
    tail: cannot open `input.dat' for reading: No such file or directory
    ./prog.pl: no match []
        3
  •  1
  •   Oleg Razgulyaev    15 年前
    open (PS,"tail -n 1 $file|");
    if($l=<PS>)
      {print"$l"}
    else
      {print"$file is empty\n"}
    
        4
  •  -1
  •   derby    15 年前

    好。。。抓挠这个…我没有把filehandle连接成管道的输出。

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