【问题标题】:Why does my chdir to a filehandle not work in Perl?为什么我对文件句柄的 chdir 在 Perl 中不起作用?
【发布时间】:2009-11-13 16:44:16
【问题描述】:

当我尝试使用文件句柄作为参数的“chdir”时,“chdir”返回 0,而 pwd 返回仍然相同的目录。应该这样吗?

我试过这个,因为在 chdir 的文档中我发现:

“在支持 fchdir 的系统上,您 可能会传递文件句柄或目录 作为论据处理。在系统上 不支持 fchdir,传递句柄 在运行时产生致命错误。”

稍后给出:

#!/usr/bin/perl -w
use 5.010;
use strict;
use Cwd;

say cwd();  # /home/mm
open( my $fh, '>', '/home/mm/Documents/foto.jpg' ) or die $!;
say chdir $fh;  # 0
say cwd();  # /home/mm

我认为这可能会 chdir 到文件的目录 - 但这里没有适合我的 DWIM。

【问题讨论】:

  • 这是哪种语言/环境?
  • 显示问题的小演示脚本在哪里?

标签: perl chdir


【解决方案1】:

它也说

成功时返回 true,否则返回 false。

表示您对chdir 的调用失败。检查$! 变量以了解发生了什么。由于您没有遇到致命的运行时错误,因此您不必担心关于fchdir 的最后一段。


运行几个测试,我看到chdir FILEHANDLE 在FILEHANDLE 引用目录而不是常规文件时有效。希望对您有所帮助:

  open(FH, "<", "/tmp/file");  # assume this file exists
  chdir FH and print "Success 1\n" or warn "Fail 1: $!\n";
  open(FH, "<", "/tmp");
  chdir FH and print "Success 2\n" or warn "Fail 2: $!\n";
  opendir(FH, "/tmp");
  chdir FH and print "Success 3\n" or warn "Fail 3: $!\n";

 

  Fail 1: Not a directory
  Success 2
  Success 3

【讨论】:

  • 啧啧,你使用的是全局类型团而不是本地词法:)
  • 我不知道,那个文件句柄可以引用一个目录。
  • @sid_com 这不是一个有用的功能,但在某种抽象层面上,Un*x 目录只是另一个文件
  • 对不起,Ether,这是一个旧的坏习惯,我仍然沉迷于短期的一次性程序。至少我开始使用open的3 arg版本@
【解决方案2】:

perl 的哪个版本?哪个操作系统?

5.10.1 在 Windows 上:

#!/usr/bin/perl

use strict; use warnings;

# have to use a file because Windows does not let 
# open directories as files
# only done so I can illustrate the fatal error on
# a platform where fchdir is not implemented

open my $fh, '<', 'e:/home/test.txt'
    or die "Cannot open file: $!";

chdir $fh
    or die "Cannot chdir using filehandle: $!";

输出:

C:\温度> k fchdir 函数在 C:\Temp\k.pl 第 9 行未实现。

Linux 上的 5.10.1(/home/sinan/test 是一个目录):

$ cat k.pl
#!/usr/bin/perl

use strict; use warnings;

use Cwd;

open my $fh, '<', '/home/sinan/test'
    or die "Cannot open file: $!";

chdir $fh
    or die "Cannot chdir using filehandle: $!";

print getcwd, "\n";

$ ./k.pl
/home/sinan/test

【讨论】:

    【解决方案3】:

    为我工作。 Windows 不支持 fchdir,实际上这是一个致命错误:

    perl -we"opendir my $fh, 'temp'; chdir $fh or print 'foo'"
    

    产生致命错误。因此,它看起来像在完全不支持 fchdir 的系统上,它符合规范。看起来措辞可以清除,尤其是“可能”这个词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多