开发者

Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so?

I tried this, because in the documentation to chdir I found:

"On systems that support fchdir, you might pass a file handle or directory handle as argument. On systems that don't support fchdir, passing handles produces a fatal error 开发者_高级运维at run time."

Given later:

#!/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

I thought that this would maybe chdir to the directory of the file - but no DWIM for me here.


It also says

It returns true upon success, false otherwise.

meaning that your call to chdir failed. Check the $! variable for a clue about what happened. Since you didn't get a fatal runtime error, you don't have to worry about that last paragraph about fchdir.


Running a couple of tests, I see chdir FILEHANDLE works when FILEHANDLE refers to a directory, but not to a regular file. Hope that helps:

  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


Which version of perl? Which operating system?

5.10.1 on 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: $!";

Output:

C:\Temp> k
The fchdir function is unimplemented at C:\Temp\k.pl line 9.

5.10.1 on Linux (/home/sinan/test is a directory):

$ 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


Works for me. Windows doesn't support fchdir and it is in fact a fatal error there:

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

produces a fatal error. So it looks like on systems that have no support for fchdir at all it works to spec. Looks like the wording could be cleared up especially the word "might."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜