in reply to Giving names to bits

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.

Replies are listed 'Best First'.
Re^2: Giving names to bits
by carcassonne (Pilgrim) on Feb 23, 2007 at 12:46 UTC
    Thanks, that works great. The only thing to do there was to initially set the status to 0 (so that vec and by ricochet logic does not complain) and then to add the actual hash set/unset to each subroutine so that it's possible to use the hash for showing the status of the individual bits easily.

    Since a hash is used, wouldn't it be possible to simply use it and let go of the $status variable i.e. when time to do so, to pack the hash 1/0 values in a byte ?

      Serves me right... that was my last option, the one I didn't give an example for ;-)