1

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

我试过这个,因为在 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。

4

3 回答 3

8

它还说

成功时返回 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
于 2009-11-13T16:50:49.017 回答
0

哪个版本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
于 2009-11-13T17:02:56.030 回答
0

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

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

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

于 2009-11-13T17:09:21.010 回答