Skip to content

Instantly share code, notes, and snippets.

@tommystanton
Created December 6, 2013 06:48
Show Gist options
  • Select an option

  • Save tommystanton/7819597 to your computer and use it in GitHub Desktop.

Select an option

Save tommystanton/7819597 to your computer and use it in GitHub Desktop.
Perl example of using bitwise operations as "flags"
# 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