bitwise and help plz

bitwise and help plz

am 15.08.2011 00:19:08 von Rajeev Prasad

--0-1556197126-1313360348=:23985
Content-Type: text/plain; charset=us-ascii

in this simple example. i am not able to figure what is the bitwise funtion doing:

my @subArray = grep { $_ & 1 } @array;

what is the significance of 1 here?

is this equivalent? { 1 & $_ }

does the EXPR inside grep's curly braces have to produce the grepped text or just a true false value? i thought like in regular shell it produces whatever it grepped.


thx.

--0-1556197126-1313360348=:23985--

Re: bitwise and help plz

am 15.08.2011 01:12:00 von Rob Dixon

On 14/08/2011 23:19, Rajeev Prasad wrote:
>
> in this simple example. i am not able to figure what is the bitwise
> funtion doing:
>
> my @subArray = grep { $_& 1 } @array;

The & operator requires the types of its operands to be identical -
either string or numeric. In either case the values are ANDed together
to produce a value of the same type.

> what is the significance of 1 here?

It is a numeric value with just bit zero set. It is ANDed with the value
in $_ so that if $_ holds an odd or even number the result will be 1 or 0.

> is this equivalent? { 1& $_ }

Yes.

> does the EXPR inside grep's curly braces have to produce the grepped
> text or just a true false value? i thought like in regular shell it
> produces whatever it grepped.

The result of the Perl grep operator is a list where the expression is
true. In this case, @subArray becomes a copy of the odd elements of
@array (those that, when ANDed with 1 are non-zero).


HTH,

Rob

--
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org
http://learn.perl.org/