1

Is there a statement that performs a simple T/F or 0/1 logical conjunction operation, returning either boolean T/F or binary or integer representations of 0 or 1 as the exclusive output?

The && and and operators, rather than returning T/F (boolean) or 0/1 (binary) return whatever value is provided as the second argument to the operator assuming both arguments are "true" (e.g., perl -e '$x=(3 && 2); print $x,"\n"' yields a value of 2; changing the statement to perl -e '$x=(3 && 4); print $x,"\n"' yields a value of 4). I am trying to find an operator that does not require either division by the final argument or an additional if statement to return strictly a 0 or 1.

My reason for seeking such an operator is to increment a counter by 0 or 1 based on the logical conjunction of two operands, and I prefer the concision of a statement such as $counter += ($x && $y), as opposed to the alternatives (e.g., if($x && $y) counter++ or $counter += ($x && $y)/$y).

Miller
  • 34,962
  • 4
  • 39
  • 60
user001
  • 1,850
  • 4
  • 27
  • 42

4 Answers4

4

You can force boolean by double negation

$counter += !!($x && $y);
mpapec
  • 50,217
  • 8
  • 67
  • 127
4

Adding a Boolean to counter (even if constrained to be only 0 or 1) has a bad code smell. The idiomatic way to do this in Perl is to use a statement modifier:

$counter++ if $x && $y;
Michael Carman
  • 30,628
  • 10
  • 74
  • 122
2

How about the ternary operator:

use warnings;
use strict;

my $val1 = 0;
my $val2 = 0; 
my $count = 0;

($val1 == 0 and $val2 == 0) ? $count++ : print "not equal\n";

print "$count\n";
fugu
  • 6,417
  • 5
  • 40
  • 75
2

You didn't realize it that you already provided the answer yourself:

The && and and operators, rather than returning T/F (boolean) or 0/1 (binary) return whatever value is provided as the second argument to the operator assuming both arguments are "true"

So what about

$boolean = $val1 && $val2 && 1;

This will evaluate to 1 if $val1 and $val2 are both true, however, if either argument is false, it will return that instead. To enforce a 0 for falses, you can build on the same principle:

$boolean = $val1 && $val2 && 1 || 0;

Although at this point it starts to become unwieldy, so perhaps the ternary operator is a better solution:

$boolean = ($val1 && $val2) ? 0 : 1;
Andrejovich
  • 544
  • 2
  • 13