This appeared in comp.lang.perl.misc recently.  (I apologize
beforehand if this is terribly old-hat.)

>I'm looking for the most compact way in Perl to take the logical
>and of all the elements of an array or list.  The best I can come
>up with is this:

>!grep !$_, @array;

>(The corresponding logical or is equally long: 

>!!grep $_, @array;

>The initial !! ensures a scalar result even in a list context.)

N.B. +grep $_, @array fails to produce a scalar output, so it is not a
shorter alternative to !!grep $_, @array.

I must say that I can't improve on these in any non-trivial way
(i.e. other than by removing unnecessary whitespace), but maybe some
fwp reader can.  Note that it is an important requirement that the
input array be an arbitrary one, not just an array of 1s and 0s.

Here's some additional commentary by the OP:

>...the grep-based solutions [ above ] have an additional virtue
>besides brevity.  They do the right thing if one wants to generalize
>the definition of the && and || operators to the "pathological" cases
>of a single operand, and no operands:

>  sub And { !grep !$_, @_ }
>  sub Or  { !!grep $_, @_ }
>  And(1)  => 1
>  And(0)  => 
>  And()   => 1
>  Or(1)   => 1
>  Or(0)   => 
>  Or()    => 

>(There are analogous generalizations for the intersection and union
>operators in set theory.)

>So this way of implementing ands and ors is not only succinct but
>also "mathematically correct" in some sense.

kj

Reply via email to