in reply to understanding if conditions

'&' is bit-wise boolean and. The expression ($i & 2**$j), is testing the binary value of $i and returns true if the $jth bit is set to one.

This may be clarified by this slightly modified version of your example code:

[11:04:18.32] P:\test>perl my $n = 4; for my $i (1..2**$n-1) { printf "%2d (0b%04b) has bits [ ", $i, $i; for my $j (0..$n-1) { if ($i & 2**$j) { print $j, " "; } # end-if } # end-for print "] set\n"; } # end-for ^Z 1 (0b0001) has bits [ 0 ] set 2 (0b0010) has bits [ 1 ] set 3 (0b0011) has bits [ 0 1 ] set 4 (0b0100) has bits [ 2 ] set 5 (0b0101) has bits [ 0 2 ] set 6 (0b0110) has bits [ 1 2 ] set 7 (0b0111) has bits [ 0 1 2 ] set 8 (0b1000) has bits [ 3 ] set 9 (0b1001) has bits [ 0 3 ] set 10 (0b1010) has bits [ 1 3 ] set 11 (0b1011) has bits [ 0 1 3 ] set 12 (0b1100) has bits [ 2 3 ] set 13 (0b1101) has bits [ 0 2 3 ] set 14 (0b1110) has bits [ 1 2 3 ] set 15 (0b1111) has bits [ 0 1 2 3 ] set

The first column is the value of $i in decimal. The second is the value of $i as binary. The numbers in []s are the positions (numbered right to left, from zero) of the bits that are set in the current value of $i.


Examine what is said, not who speaks.
"But you should never overestimate the ingenuity of the sceptics to come up with a counter-argument." -Myles Allen
"Think for yourself!" - Abigail        "Time is a poor substitute for thought"--theorbtwo         "Efficiency is intelligent laziness." -David Dunham
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

Replies are listed 'Best First'.
Re^2: understanding for loops
by rsiedl (Friar) on Nov 21, 2004 at 11:14 UTC
    Thanks BrowserUk!