What MySQL basically does is assign each set value a number, then uses those numbers to set and clear bits in an integer. For example:
use constant GENRE_ROCK => 0;
use constant GENRE_POP => 1;
use constant GENRE_JAZZ => 2;
use constant GENRE_METAL => 3;
use constant GENRE_LAST => 3;
sub pack_set
{
my $bits == 0;
foreach my $genre (@_)
{
$bits |= (1<<$genre);
}
$bits;
}
sub unpack_set
{
my($bits)=@_;
my @ret = ();
my $i = 0;
while ($bits)
{
if ($bits & 1)
{
push(@ret,$i);
}
$i++;
$bits >>= 1;
}
@ret;
}
my $ella = pack_set(GENRE_POP, GENRE_JAZZ);
warn "Packed set is $ella\n";
print "Ella's Genres: ";
foreach my $genre (unpack_set($ella))
{
$genre == GENRE_ROCK and print "rock ";
$genre == GENRE_POP and print "pop ";
$genre == GENRE_JAZZ and print "jazz ";
$genre == GENRE_METAL and print "metal ";
}
print "\n";
Storing the numbers in a hash instead of with constants would make it easier to print them.
|