tags:

views:

359

answers:

3

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.

+8  A: 
mobrule
Tsk tsk, you're using a global typeglob rather than a local lexical :)
Ether
I didn't know, that filehandle can refer to a directory.
sid_com
@sid_com It's not a useful feature, but at some level of abstraction a Un*x directory is just another file
mobrule
Sorry Ether, it's an old bad habit that I still indulge on short throwaway programs. At least I started using the 3 arg version of `open`
mobrule
A: 

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
Sinan Ünür
A: 

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."

Dan