in reply to diamond operator question

A Unix directory may be implemented as a file with one entry per file, but that doesn't necessarily equate to one line of a text file. The precise format of the file is a low-level implementation detail and I doubt it would be the same on all variants of Unix. If I type cat . on HP-UX I just get gibberish, containing recognisable filenames plus a load of binary stuff - and no line-ends.


s^^unp(;75N=&9I<V@`ack(u,^;s|\(.+\`|"$`$'\"$&\"\)"|ee;/m.+h/&&print$&

Replies are listed 'Best First'.
Re^2: diamond operator question
by Tomtom (Scribe) on Jun 09, 2005 at 08:46 UTC
    Is there a reason why the diamond operator in Perl doesn't call readdir for directories, the same way it calls readline for regular files ?

      I suppose they could have done that, but I can't comment on why they didn't. It would have to be able to detect whether it was working on a filehandle created by open or a dir handle created by opendir, but I guess that's not unreasonable.


      s^^unp(;75N=&9I<V@`ack(u,^;s|\(.+\`|"$`$'\"$&\"\)"|ee;/m.+h/&&print$&
        Excuse me for keeping asking questions about this :) but it's for my own curiosity :

        What could be the different ways to detect the kind of filehandle, to know if it was opened by open or opendir ?
        Apparently, the following quote :
        "DIRHANDLEs have their own namespace separate from FILEHANDLEs." (source)
        could help detecting whether it was opened by open or opendir.
        But when I do something like the following code to see the difference between the two namespaces, I get the same result for both of them.
        open(DIR, './random_file'); print 'open : ', *main::DIR{NAME}, ' - ', *main::DIR{PACKAGE}, "\n"; opendir (DIR, '.'); print 'opendir : ', *main::DIR{NAME}, ' - ', *main::DIR{PACKAGE}, "\n" +;
        Am I doing something wrong, or is there another way to differentiate the namespaces of the handles ?
        Or could it be the version of Perl I'm using ( 5.005 ) ?

        Thanks

      Orthagonality with the C opendir(2) and friends would be my guess. If it really mattered to you you probably could implement a tied filehandle that provided its own map from readline to readdir without too much trouble.

      Update: Yeah, not too much trouble at all.

      #!/usr/bin/perl use strict; package Tie::Dirfile; use IO::Dir (); sub TIEHANDLE { my $class = shift; my $self = {}; $self->{_dir} = shift; $self->{_handle} = IO::Dir->new( $self->{_dir} ); return bless $self, $class; } sub READLINE { return shift()->{_handle}->read; } sub CLOSE { return shift()->{_handle}->close( ); } package main; local( *DH ); tie *DH, 'Tie::Dirfile' => "/bin" or die "Can't create Tie::Dirfile for /bin: $!\n"; my $i = 0; print $i++, ": ", $_, "\n" while( <DH> ); close( DH ); exit 0; __END__

      --
      We're looking for people in ATL