ビット演算による権限制御

 #!/usr/bin/env perl
 
 use strict;
 use warnings;
 use 5.012;
 
 # 権限を設定
 my $none    = 0x0;
 my $read    = 0x1 << 0;
 my $write   = 0x1 << 1;
 my $execute = 0x1 << 2;
 my $extra   = 0x1 << 3;
 my $all = $none | $read | $write | $execute;
 
 my %actions = (
     +read    => $read,
     +write   => $write,
     +execute => $execute,
     +extra   => $extra,
 );
 
 # 権限を2進数で確認
 printf( "%- 10s%04b\n", "none",    $none );
 printf( "%- 10s%04b\n", "read",    $read );
 printf( "%- 10s%04b\n", "write",   $write );
 printf( "%- 10s%04b\n", "execute", $execute );
 printf( "%- 10s%04b\n", "extra",   $extra );
 printf( "%- 10s%04b\n", "all",     $all );
 
 say '';
 
 # 各権限の内容を確認
 if (($all & $read) != 0) {
     say "all can read ? => OK";
 } else {
     say "all can read ? => NG";
 }
 
 if (($write & $read) != 0) {
     say "write can read ? => OK";
 } else {
     say "write can read ? => NG";
 }
 
 if (($read & $execute) != 0) {
     say "read can execute ? => OK";
 } else {
     say "read can execute ? => NG";
 }
 
 say '';
 
 while ( my ( $k, $v ) = each %actions ) {
     if ( ( $all & $v ) != 0 ) {
         say "all can $k ? => OK";
     }
     else {
         say "all can $k ? => NG";
     }
 }
 
 say '';
 
 while ( my ( $k, $v ) = each %actions ) {
     if ( ( $extra & $v ) != 0 ) {
         say "extra can $k ? => OK";
     }
     else {
         say "extra can $k ? => NG";
     }
 }

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS