Well, if you only ever have "r", "w", "x", and "-" present, then you can use pack/unpack for this:

sub perm2mode { my( $perm )= @_; if( 9 != length($perm) || 9 != ( $perm =~ tr/rwx-/1110/ ) ) { die "Unsupported permission string ($_[0])"; } return unpack "v", pack "b*", ''.reverse$perm; }
Use sprintf "0%o" on the return value if you want an octal string, but don't try to use that octal string as a number or you'll get the wrong number:
my $mode= perm2mode("rw-r----x"); my $str= sprintf "0%o", $mode; print "mode=$mode str=$str\n"; my $bad= 0+$str; printf "bad=%d=0%o mode=%d=0%o\n", $bad, $bad, $mode, $mode;
produces:
mode=417 str=0641 bad=641=01201 mode=417=0641
So, for example, using chmod $str, $file; would be wrong just like chmod "0660", $file; is.

        - tye (but my friends call me "Tye")

In reply to (tye)Re: Converting Permissionstring to Octal by tye
in thread Converting Permissionstring to Octal by stefan k

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.