A bit of creativity with constant and vec would probably be the way I'd go about it if I wanted precisely the code you had. More likely, though, would be that I'd take strings, and convert to a number in a hash, and then use vec. More likely still, I'd just leave everything as a hash (yeah, waste a lot of memory), and then pack it all together at the last minute when I actually had to send it somewhere in binary format (if such a requirement was actually there). No, I don't concern myself with memory too much these days.

Example 1:

use constant powerOn => 0; use constant lightOn => 1; { my $status; sub setStatus { my $bit = shift; vec($status, $bit, 1) = 1; } sub resetStatus { my $bit = shift; vec($status, $bit, 1) = 0; } sub getStatus { my $bit = shift; vec($status, $bit, 1); } }
Example 2:
{ my $status; my %types = ( powerOn => 0, lightOn => 1 ); sub _bit { if (exists $types{$_[0]}) { $types{$_[0]} } else { die "Unk +nown bit $_[0]"} } sub setStatus { my $bit = _bit(shift); vec($status, $bit, 1) = 1; } # etc. } # call as... setStatus('powerOn');
I don't think the last one needs an example.

Update: missing close-brace, as pointed out by fenLisesi.


In reply to Re: Giving names to bits by Tanktalus
in thread Giving names to bits by carcassonne

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.