How can i do this in perl, shortcut truthtable [closed]

Translating the matrix into code is quite simple.

sub Z {
   my ($C2, $C1, $B2, $B1, $A) = @_;
   return 1 if $C2 && $C1;
   return 1 if $B2 && $B1;
   return 1 if $A;
   return 0 if !$C2 && !$B1 && !$A;
   return 0 if !$C1 && !$B1 && !$A;
   return 0 if !$C2 && !$B2 && !$A;
   return 0 if !$C1 && !$B2 && !$A;
   croak("Should never be reached");
}

Since all possible inputs will result in one of the returns being executed, the above simplifies to the following:

sub Z {
   my ($C2, $C1, $B2, $B1, $A) = @_;
   return 1 if $C2 && $C1;
   return 1 if $B2 && $B1;
   return 1 if $A;
   return 0;
}

We can easily write that as one line.

my $Z = $C2 && $C1 || $B2 && $B1 || $A;           # If $Z needs to be true or false.
my $Z = $C2 && $C1 || $B2 && $B1 || $A ? 1 : 0;   # If $Z needs to be 0 or 1 specifically.

Browse More Popular Posts

Leave a Comment