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

如何检查Perl中是否打开了文件句柄?[副本]

  •  35
  • Matt  · 技术社区  · 17 年前

    是否有方法检查文件是否已在Perl中打开? 我想有读取文件的权限,所以不需要 flock .

     open(FH, "<$fileName") or die "$!\n" if (<FILE_IS_NOT_ALREADY_OPEN>);
     #  or something like
     close(FH) if (<FILE_IS_OPEN>);
    
    5 回复  |  直到 16 年前
        1
  •  38
  •   Community Mohan Dere    9 年前

    请查看 answer regarding openhandle() from Scalar::Util 我最初在这里写的答案曾经是我们能做的最好的,但现在已经严重过时了。

        2
  •  23
  •   Community Mohan Dere    5 年前

    这个 Scalar::Util 模块提供 openhandle() 功能为此。不像 fileno() ,它处理与操作系统文件句柄不相关的perl文件句柄。不像 tell() ,在未打开的文件句柄上使用时,它不会产生警告 documentation :

    开放式手柄FH

    Returns FH if FH may be used as a filehandle and is open, or FH is a tied handle. Otherwise "undef" is returned.
    
       $fh = openhandle(*STDIN);           # \*STDIN
       $fh = openhandle(\*STDIN);          # \*STDIN
       $fh = openhandle(*NOTOPEN);         # undef
       $fh = openhandle("scalar");         # undef
    
        3
  •  11
  •   Leon Timmermans    17 年前

    你为什么要这么做?我能想到的唯一原因是,当您使用旧式包文件句柄(您似乎正在这样做)并希望防止意外将一个句柄保存在另一个句柄上时。

    这个问题可以通过使用新样式的间接文件句柄来解决。

    open my $fh, '<', $filename or die "Couldn't open $filename: $!";
    
        4
  •  9
  •   chaos    16 年前

    Perl提供 fileno 正是为了这个目的。

    编辑 我接受纠正的目的是 fileno() 我确实更喜欢较短的测试

    fileno FILEHANDLE

    结束

    tell FH != -1

        5
  •  1
  •   CoffeeMonster    16 年前

    Tell会产生一个警告(stat、-s、-e等也是如此。) use warnings w

    perl -wle '
        open my $fh, "<", "notexists.txt"; 
        print "can stat fh" if tell $fh
    '
    tell() on closed filehandle $fh at -e line 1.
    -1
    

    替代方案 fileno($fh) eof($fh) 不要发出警告。 我发现最好的选择是节省输出 open .

    推荐文章