hackdaddy has asked for the wisdom of the Perl Monks concerning the following question:

I need to convert the ls permissions listing string of -rwxr-xr-x into mode for use with stat.

I am taking the output of a gtar -tzvf and converting it into mode for comparison with the output of stat.

Unfortunately, I am not able to find complete examples of this task. Any assistance would be greatly appreciated. Thanks.

hackdaddy
  • Comment on Convert ls listing of -rwxr-xr-x into mode for stat

Replies are listed 'Best First'.
Re: Convert ls listing of -rwxr-xr-x into mode for stat
by gav^ (Curate) on Apr 18, 2002 at 04:04 UTC
    You might want to look at the source for File::Listing (a module that parses the result of ls -l).

    gav^

Re: Convert ls listing of -rwxr-xr-x into mode for stat
by Fletch (Bishop) on Apr 18, 2002 at 03:49 UTC

    You could always just use Archive::Tar and get the mode directly without parsing anything.

Re: Convert ls listing of -rwxr-xr-x into mode for stat
by Kanji (Parson) on Apr 18, 2002 at 04:02 UTC

    Have you looked at Stat::lsMode (alt.)?

    It's aimed more towards the inverse of what you're doing, but there's an undocumented function called lsmode that might be of interest...

        --k.


Re: Convert ls listing of -rwxr-xr-x into mode for stat
by ferrency (Deacon) on Apr 18, 2002 at 17:07 UTC
    Writing your own solution sounds like a good golf problem.

    Assuming you have a valid 9 digit mode string with -'s where the bits are off, here's a small snippet that'll usually do what you want:

    $_ = "-r-x-w-rwx"; # Mode string in $_ my $bits = 0; for (split //) { $bits *= 2; $_ ne "-" and $bits++; } printf "My bits are: %o\n", $bits;
    Not completely size optimized, but perhaps a bit easier to understand this way.

    The basic technique is to loop through the string, checking each character to see whether it's a "-" (off bit) or not (on bit). Each time through the loop, multiply $bits by 2 to shift the previous result out of the way, and then add 1 if the lowest bit should be turned on.

    This does not detect the setuid or setgid bits, or anything other than standard drwxrwxrwx bits correctly.

    Alan