in reply to Taking arbitrary elements from an array

Something for other novices who may be watching this thread :)

Having played about with this for a while now, I've found what works... and a little bit as to why...

The primary thing seems to be that the number of elements in the array must match the number of bits supplied in the integer map; that is, if you have 13 options in an array, you must have a 13-bit value integer (or express it in 16-bits with extra '0's in the MSB). To make this simpler to see in the code, I think it helps to specify the mask value as a binary value.

With this in mind, I've explored demerphq's suggestion and have found it to be the one that reliably works (with Active State perl under WinXP anyway). Here's an example:

my @arr = qw (and you will be pleased with the results now we have it +working ); # 1 0 1 0 1 0 1 1 0 1 0 0 +1 my $mask = 0b1010101101001; # For clarity # $mask = 0b0001010101101001; # Force to byte boundary # $mask = 0x1569; # ...if you prefer to think in nybbl +es my @result = wave_hands( $mask, @arr ); my $n = @arr; printf("The array contains $n elements\n"); print "@result"; # "and will pleased the results we working" sub wave_hands { my $mask=0+shift; my $i=1; my @r; for ( my $p=$#_ ; $p>=0 && $i<=$mask ; $p-- ) { unshift @r,$_[$p] if $mask & $i; $i<<=1; } return @r; } # end wave_hands