Created
December 6, 2013 06:48
-
-
Save tommystanton/7819597 to your computer and use it in GitHub Desktop.
Perl example of using bitwise operations as "flags"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Based on this tutorial: | |
| # http://www.devshed.com/c/a/Perl/Perl-Bit-by-Bit/3/ | |
| # | |
| # This will print: | |
| # | |
| # .--------------------------------. | |
| # | Name | Programmer? | Adult? | | |
| # +---------+-------------+--------+ | |
| # | Bob | Yes | Yes | | |
| # | Alice | No | Yes | | |
| # | Carol | Yes | No | | |
| # | Mallory | No | No | | |
| # '---------+-------------+--------' | |
| use strict; | |
| use warnings; | |
| use Text::ASCIITable; | |
| use constant { | |
| IS_PROGRAMMER => 0b01, | |
| IS_ADULT => 0b10, | |
| }; | |
| my $table = Text::ASCIITable->new; | |
| $table->setCols( 'Name', 'Programmer?', 'Adult?' ); | |
| add_to_table( 'Bob', IS_PROGRAMMER | IS_ADULT ); # 0b11 | |
| add_to_table( 'Alice', IS_ADULT ); # 0b10 | |
| add_to_table( 'Carol', IS_PROGRAMMER ); # 0b01 | |
| add_to_table( 'Mallory', 0b00 ); | |
| print $table; | |
| sub add_to_table { | |
| my ( $name, $flags ) = @_; | |
| $table->addRow( | |
| $name, | |
| $flags & IS_PROGRAMMER ? 'Yes' : 'No', | |
| $flags & IS_ADULT ? 'Yes' : 'No', | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment