Harry Putnam wrote:
> "Rob Dixon" <[EMAIL PROTECTED]> writes:
>
> > So you can use:
> >
> >   if (-f $file) {
> >     :
> >     # process file
> >   }
> >   elsif (-d $file) {
> >     :
> >     # process directory
> >   }
>
> Well, yes of course I can run each filename thru all those tests, but
> that seems kind of like a lot of huffing and puffing.  I wondered if
> there isn't something that just spits it out.
>
> perl `stat' does do that very thing in element[2] ($mode) but extracting
> `type' from that number looks hideously complicated.
>
> Maybe running all possible tests is quicker and easier after all.
> It would really come down to just these:
>     -f -d -l -b -c -p -S
> But all that info is available in @elems = (stat "fname");
>
> Unix `stat' actually spits it out in plain english, what type it is.
> (at least gnu `stat' does)

OK, I misunderstood you. Yes, you can use the 'stat' call, but what
you get back is dependent on the platform you're using. The file
test operators are nice because they hide all that from you.

This code will build a map of 'stat' type values to the seven type
operators that you list. Not all of them may be active on your system.
You can obviously modify the code to return the value you want.
You need to import the symbolic mode values using Fcntl before this
will work.

Let us know if anything needs explaining.

HTH,

Rob


  use strict;
  use Fcntl ':mode';

  print filetype('/home/rob/dir'), "\n";
  print filetype('/home/rob/script'), "\n";

  {
    my %types;

    sub filetype {

      unless ( %types ) {
        @types{ map eval || '', qw/S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR S_IFIFO 
S_IFSOCK/ }
            = qw/-f -d -l -b -c -p -S/;
        delete $types{''};
      }

      my $file = shift;
      my $type = (stat $file)[2] & S_IFMT;

      return $types{$type};
    }
  }

>> OUTPUT

  -d
  -f










-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to