in reply to Re: What is the perl equivelant to a 'Set' column type in mysql?
in thread What is the perl equivelant to a 'Set' column type in mysql?

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.

Replies are listed 'Best First'.
Re: Re: Re: What is the perl equivelant to a 'Set' column type in mysql?
by tachyon (Chancellor) on May 01, 2004 at 18:06 UTC

    Small logic nit. The set bits are 0 1 2 4 8.... In your example a jazzy pop band would be a metal entity as well as a last....It is also worth noting that you can only rely on 31-32 (sign bit) genres unless you can guarantee long 64 bit ints.

    cheers

    tachyon

      I think you missed the part where I used the sequential numbers as a count for which bits to set or check; if not please elaborate, as I don't see the bug. In fact, the example I gave is a jazzy pop singer, and it works properly.

      Using powers of 2 for the constants is a good idea, though; I just thought it would be easier to explain this way.

        My mistake, I did not read the code carefully and ignored the bitshift logic ;-). I use OR logic for my masks

        my %genres = ( ROCK => 0, POP => 1, JAZZ => 2, } my $bits = 0; $bits |= $genres{$_} for @spec;

        cheers

        tachyon

Re: Re: Re: What is the perl equivelant to a 'Set' column type in mysql?
by nmerriweather (Friar) on May 01, 2004 at 00:34 UTC
    awesome -- I knew thats the logic behind how mysql did it, I just didn't know the way it processed it you rock. like a hurricane.