I'm almost embarrassed to ask this, but I can't figure out a simple way to 
construct a switch ('given') statement where the 'when' clauses involve 
bit-testing.

Here's the only way I've figured out to build a switch statement that does the 
trick.  It seems unusually wordy, which makes me think there must be a simpler 
way to test for certain bit combinations.  Any suggestions?

Thanks,
Chap

#!/usr/bin/perl                                                                 
                                                                                
                                         

use strict;
use warnings;
use feature ":5.10";

# Here are masks for various bit combos of interest:                            
                                                                                
                                          

my $one_three        = 0b00001010; # bits 1 and 3 (counting from 0, right to 
left)                                                                           
                                             
my $zero_four        = 0b00010001; # bits 0 and 4                               
                                                                                
                                         
my $five             = 0b00100000; # bit 5                                      
                                                                                
                                          

# Here we will test several bit fields for bit combos of interest:              
                                                                                
                                          

for my $flags ( 0b10111010, 0b10111000, 0b10010010) {

    my $asbits = sprintf("0b%08b", $flags); # prepare bits for pretty-printing  
                                                                                
                                          

    given ( $flags ) {
        when ( ($_ & $one_three) == $one_three ) {  # bits one and three are on 
                                                                                
                                         
            say "$asbits has bits 1 and 3";
        }
        when ( ($_ & $zero_four) == $zero_four ) { # bits zero and four are on  
                                                                                
                                          
            say "$asbits has bits 0 and 4";
        }
        when ( ($_ & $five) == $five ) { # bit five is on                       
                                                                                
                                         
            say "$asbits has bit 5";
        }
        default {
            say "$asbits has no interesting bit patterns.";
        }
    }
}



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to