I'm still thinking about it, but I think this is more or less what you need (there might be a module that does this on CPAN; "enum" comes pretty close) :

use strict; package Bit; use Tie::Scalar; sub TIESCALAR { my ($self) = bless {}, shift; $self->{ref} = shift; $self->{mask} = shift; $self->{bit} = 0; return $self unless $self->{mask}; # mask can't be zero my $tmp = $self->{mask}; while ( !($tmp & 1)) { $tmp >>= 1; $self->{bit} ++; } return $self; } sub FETCH { my $self = shift; return ( ${$self->{ref}} & $self->{mask} ) >> $self->{bit} ; } sub STORE { my $self = shift; my $value = shift; ${$self->{ref}} |= $self->{mask}; ${$self->{ref}} ^= $self->{mask}; ${$self->{ref}} |= $self->{mask} & ($value << $self->{bit}); } #--------------------- my $bits = 0; # a "n-bits" variable tie my $a, 'Bit', \$bits, 0x07; # bits 0..3 are $a tie my $b, 'Bit', \$bits, 0x70; # bits 4..7 are $b $a = 1; print "$bits\n"; # 1 $b = 1; print "$bits\n"; # 17 $a = 0; print "$bits\n"; # 16

update: - The "bit" parameter is calculated by TIESCALAR.
- Using "vec" instead of bitwise operations is a good idea.
- Added "mask can't be zero" test.


In reply to Re: Named Bits in a 32-bit integer by fglock
in thread Named Bits in a 32-bit integer by RollyGuy

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.