in reply to Re: Unix File Type with stat
in thread Unix File Type with stat

I am wanting to see if my file is a link without having to rerun the stat operator. I saw an note in O'Reilly Perl book that stated that when returning info on a link, stat would return the filetype of the actual file (- , d, etc...). So maybe I should re-phrase my question to: Is there a way to have an algorithm that will tell me what type of file it is without having to check each specific bit. The following code returns a - for the file which is a link in both the $filelink and the $filetype variables.
# hard code a test link file to check $source_file = "/temp/test/source/dir1/hello1_link.txt"; # define filetype array with potential first bits of mode @ftypes = qw(. p c ? d ? b ? - ? l ? s ? ? ?); $ftypes0 = ''; # Get File Statistics Using Scalar context ($dev,$inode,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($source_file); $perms = $mode & 07777; $octperms = sprintf("%lo", $perms); $filetype = $ftypes[($mode & 0170000)>>12]; $filelink = $ftypes[($mode & 0120000)>>12];
And while I am admitting how much I don't know, what does the >>12 do in the array reference? Thanks.

Replies are listed 'Best First'.
Re: Re: Unix File Type with stat
by Helter (Chaplain) on Sep 10, 2002 at 13:09 UTC
    I can answer the last part about the bit shift operator.
    >> 12 takes the number to the left and shifts it 12 bits to the right.
    << 12 would shift it 12 bits to the left.
    In octal there are 3 bits per character shown (is this still called a nibble? Or is that only 4 bits, I don't play in octal that often :)
    So this will bitwise and $mode with 0170000 and then shift it down so that the bottom 4 zero's go away.
    0170000 >> 12 = 017
    Hope this helps!
Re: Re: Unix File Type with stat
by Zaxo (Archbishop) on Sep 10, 2002 at 15:57 UTC

    You should use the lstat builtin if you don't want to resolve soft links.

    If you use Fcntl qw(:mode); you can get the constants by name. That will be easier to read and remember.

    ++Helter for the other answers.

    After Compline,
    Zaxo