Because it's a bitwise AND.

123 = 1111011 4 = 0000100 ^

The operator '&' returns a value where each bit of one value is is ANDed against each bit of the other value.

The marked digit is 1 for the value 4, and 0 for value 123. The rest of the digits are 1 for value 123 and 0 for 4. When you do an AND of each bit in this case, there are no bits which are 1 in both values. That's why you get a value with no bits set to 1, which is 0.

It'll help if you stop thinking of '&' and '|' as mathematical operators and thinking of them as boolean logical tests against vectors of bits, which is essentially what they are.

From perlop:

Bitwise And

Binary "&" returns its operands ANDed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)

Note that "&" has lower priority than relational operators, so for example the brackets are essential in a test like

print "Even\n" if ($x & 1) == 0;

Bitwise Or and Exclusive Or

Binary "|" returns its operands ORed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)

Binary "^" returns its operands XORed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)

Note that "|" and "^" have lower priority than relational operators, so for example the brackets are essential in a test like

print "false\n" if (8 | 2) != 10;

In reply to Re^3: Bitwise and operator question by mr_mischief
in thread Bitwise and operator question by Severy

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.