我可以从Perl的文件句柄中找到文件名吗? [英] Can I find a filename from a filehandle in Perl?

查看:85
本文介绍了我可以从Perl的文件句柄中找到文件名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

open(my $fh, '>', $path) || die $!;
my_sub($fh);

my_sub()可以以某种方式从$ fh推断$ path吗?

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

推荐答案

文件句柄甚至可能不连接到文件,而是连接到网络套接字或钩接到子进程的标准输出的管道.

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.

如果要将句柄与打开代码的路径相关联,请使用哈希和 fileno 运算符, eg

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

这篇关于我可以从Perl的文件句柄中找到文件名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆