'&' 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

In reply to Re: understanding for loops by BrowserUk
in thread understanding if conditions by rsiedl

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.