All pastes #262651 Raw Edit

perms

public text v1 · immutable
#262651 ·published 2006-11-30 19:39 UTC
rendered paste body
#!/usr/bin/perl
#
# perms - show the rwx pattern for a given mode
# Usage: perms 123
# prints:
# ---x-w--wx 0123
#

use warnings;
use strict;

sub show_flag ($$$) {

    my ( $place, $mask, $oct ) = ( shift, shift, shift );

    my @flag = qw(- - -);

    if ( $oct >= 4 ) {

        $flag[0] = "r";
        $flag[1] = "w" if ( $oct >= 6 );    # 6,7

    }
    else {

        $flag[1] = "w" if ( $oct >= 2 );    # 2,3

    }

    if ( $place == 1 && $mask % 2 ) {

        $flag[2] = do { $oct % 2 } ? "t" : "T";

    }
    elsif ( $place == 3 && $mask >= 4 ) {

        $flag[2] = do { $oct % 2 } ? "s" : "S";

    }
    elsif ( $place == 2 && ( $mask == 2 || $mask == 3 || $mask >= 6 ) ) {

        $flag[2] = do { $oct % 2 } ? "s" : "S";

    }
    else {

        $flag[2] = do { $oct % 2 } ? "x" : "-";

    }

    return join( "", @flag );

}

my ( $m, $u, $g, $o );

if ( $#ARGV == 0 ) {

    my $perms = shift;

    $perms = "0" . $perms if ( $perms =~ /^[0-7]{3}$/ );

    if ( $perms =~ /^[0-7]{4}$/ ) {

        ( $m, $u, $g, $o ) = split( //, $perms );

        printf(
            "-%s%s%s $m$u$g$o\n",
            show_flag( 3, $m, $u ),
            show_flag( 2, $m, $g ),
            show_flag( 1, $m, $o )
        );

    }
    elsif ( $perms =~ /^-([-r][-w][-xSs]){2}([-r][-w][-xTt])$/ ) {

        for $m ( 0 .. 7 ) {

            for $u ( 0 .. 7 ) {

                for $g ( 0 .. 7 ) {

                    for $o ( 0 .. 7 ) {

                        if (
                            $perms =~ sprintf( "-%s%s%s",
                                show_flag( 3, $m, $u ),
                                show_flag( 2, $m, $g ),
                                show_flag( 1, $m, $o ) )
                        ) {

                            print "$perms $m$u$g$o\n";

                        }

                    }

                }

            }

        }

    }

}
else {

    for $m ( 0 .. 7 ) {

        for $u ( 0 .. 7 ) {

            for $g ( 0 .. 7 ) {

                for $o ( 0 .. 7 ) {

                    printf(
                        "-%s%s%s $m$u$g$o\n",
                        show_flag( 3, $m, $u ),
                        show_flag( 2, $m, $g ),
                        show_flag( 1, $m, $o )
                    );

                }

            }

        }

    }

}

#
# NB: This could be golfed into something a lot sexier!
# It was a quick knock-up to figure out the logic.
#