Can I find a filename from a filehandle in Perl?

后端 未结 3 879
逝去的感伤
逝去的感伤 2020-12-10 01:53
open(my $fh, \'>\', $path) || die $!;
my_sub($fh);

Can my_sub() somehow extrapolate $path from $fh?

3条回答
  •  攒了一身酷
    2020-12-10 02:35

    A filehandle might not even be connected to a file but instead to a network socket or a pipe hooked to the standard output of a child process.

    If you want to associate handles with paths your code opens, use a hash and the fileno operator, e.g.,

    my %fileno2path;
    
    sub myopen {
      my($path) = @_;
    
      open my $fh, "<", $path or die "$0: open: $!";
    
      $fileno2path{fileno $fh} = $path;
      $fh;
    }
    
    sub myclose {
      my($fh) = @_;
      delete $fileno2path{fileno $fh};
      close $fh or warn "$0: close: $!";
    }
    
    sub path {
      my($fh) = @_;
      $fileno2path{fileno $fh};
    }
    

提交回复
热议问题