Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何判断Perl中的文件句柄是否为空?_Perl_Filehandle - Fatal编程技术网

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

如何判断Perl中的文件句柄是否为空?,perl,filehandle,Perl,Filehandle,例如: open (PS , " tail -n 1 $file | grep win " ); 我想确定文件句柄是否为空。您还可以使用检查文件句柄是否已用尽。下面是一个大致基于您的代码的示例。还请注意3-arg形式的词法文件句柄的使用 open (PS,"tail -n 1 $file|"); if($l=<PS>) {print"$l"} else {print"$file is empty\n"} 嗯。。。把这个擦掉。。。我没有把filehandle连接成管道的输出

例如:

open (PS , " tail -n 1 $file | grep win " );
我想确定文件句柄是否为空。

您还可以使用检查文件句柄是否已用尽。下面是一个大致基于您的代码的示例。还请注意3-arg形式的词法文件句柄的使用

open (PS,"tail -n 1 $file|");
if($l=<PS>)
  {print"$l"}
else
  {print"$file is empty\n"}

嗯。。。把这个擦掉。。。我没有把filehandle连接成管道的输出

您应该使用来确定文件的大小,但您需要 确保先刷新文件:

#!/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;
尽管在您尝试读取eof之前调用eof会产生您在这种特定情况下所期望的结果,但请注意报告末尾的建议:

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

您的命令最多生成一行,因此请将其固定在标量中,例如

请注意,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: 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 []
你想做什么?您是否更关心文件是否存在或文件是否为空?执行此操作后,我想找出PS是否为空!
#! /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 []