2 # ABSTRACT: Test if expressions are logically equivalent
3 # PODNAME: test-logical-equivalence
7 use warnings FATAL => 'all';
11 use Acme::Test::LogicalEquivalence qw(is_logically_equivalent);
16 Test if two simple expressions are logically equivalent.
18 Exactly two expressions must be given.
20 Example: $0 '\$a || \$b' '\$b || \$a'
21 Remember that you may need to escape special characters like "\$" from your shell.
31 # check for scalars that look like $a or $b
32 for my $varname ($expr =~ /\$([a-z])/g) {
33 my $num = ord($varname) - 97;
34 $highest = $num if $highest < $num;
37 # check for scalars that index $_
38 for my $varname ($expr =~ /\$_\[(\d+)\]/g) {
40 $highest = $num if $highest < $num;
46 my $expr1 = shift or usage;
47 my $expr2 = shift or usage;
49 my $numvars1 = find_num_vars($expr1);
50 my $numvars2 = find_num_vars($expr2);
51 my $num = $numvars1 > $numvars2 ? $numvars1 : $numvars2;
54 print STDERR 'No variables detected. Variables should be one or more of $a, $b, ..., $z', "\n";
58 # convert $a-style vars to $_[0]-style to support more than just $a and $b
59 $expr1 =~ s/\$([a-z])/'$_['.(ord($1) - 97).']'/ge;
60 $expr2 =~ s/\$([a-z])/'$_['.(ord($1) - 97).']'/ge;
62 my $sub1 = eval "sub { $expr1 }" or die "Expression 1: $@\n"; ## no critic (ProhibitStringyEval)
63 my $sub2 = eval "sub { $expr2 }" or die "Expression 2: $@\n"; ## no critic (ProhibitStringyEval)
65 plan tests => (2 ** $num);
66 note "Testing for logical equivalence of two expressions with $num variable(s)...";
68 my $equivalence = is_logically_equivalent($num, $sub1, $sub2);
69 note $equivalence ? 'Logical equivalence proved!' : 'Bummer...';
79 test-logical-equivalence - Test if expressions are logically equivalent
87 # be sure to escape $ and other special characters from your shell
88 test-logical-equivalence '$a && $b' '$b && $a'
96 L<Acme::Test::LogicalEquivalence>
102 Charles McGarvey <chazmcgarvey@brokenzipper.com>
104 =head1 COPYRIGHT AND LICENSE
106 This software is copyright (c) 2016 by Charles McGarvey.
108 This is free software; you can redistribute it and/or modify it under
109 the same terms as the Perl 5 programming language system itself.