I'm not convinced that you need an elegant solution to finding if one and only one of three elements evaluates to truth. But it's kind of a fun problem anyway, and if the number of elements grows, a sleek solution becomes more relevant. So here goes...

Try cpan's List::MoreUtils:

use strict; use warnings; use List::MoreUtils qw/ true /; my @lists = ( [ 1, 0, 1 ], [ 1, 0, 0 ], [ 1, 1, 1 ], [ 0, 0, 0 ] ); foreach my $aref ( @lists ) { print "Testing @{$aref}\n"; print "Total list Exclusive OR ", ( 1 == true { $_ } @{ $aref } ) ? '' : 'not ', "satisfied.\n\n"; }

Here we're just using the true() function from List::MoreUtils. The function returns the number of true elements. Like one of your proposed solutions, we simply check to ensure that the number of true elements is exactly one. This one works almost identically to your grep solution, except that it uses an explicit function name (true()) instead of a generic one such as grep.

My example snippet actually tests a list of lists to see if each sub-list individually satisfies your requirement of a single element of truth. The engine is this:

1 == true { $_ } @array

If that test evaluates to truth, you've got a list with a single element of truth.


Dave


In reply to Re: One out of three ain't bad by davido
in thread One out of three ain't bad by saintmike

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.