in reply to Re^2: IF condition with a range
in thread IF condition with a range
To build on tobyink's post, remember that it's easy to try things out:
Updated with the Inf test case suggested by syphilis.
use warnings; use strict; my @testcases = ( [1,-1], [1,0], [1,1], [1,2], [1,3], [9**9999,9**9999] ); for my $sub (qw/ doit1 doit2 doit3 doit4 /) { print "-----\n"; for my $testcase (@testcases) { print "$sub($testcase->[0], $testcase->[1]):\n"; # for this test only, not recommended otherwise: no strict 'refs'; &{$sub}(@$testcase); } } sub doit1 { my ($x,$y) = @_; if ($x==$y) { print "\tThey are equal, do something\n"; } if (abs($y-$x)<=1) { print "\tThey are within +/- 1, do something else\n"; } } sub doit2 { my ($x,$y) = @_; if ($x==$y) { print "\tThey are equal, do something\n"; } elsif (abs($y-$x)<=1) { print "\tThey are within +/- 1, do something else\n"; } } sub doit3 { my ($x,$y) = @_; if (abs($y-$x)<=1) { print "\tThey are within +/- 1, do something else\n"; } elsif ($x==$y) { print "\tThey are equal, do something\n"; } } sub doit4 { my ($x,$y) = @_; if (abs($y-$x)<=1) { if ($x==$y) { print "\tThey are equal, do something\n"; } print "\tThey are within +/- 1, do something else\n"; } } __END__ ----- doit1(1, -1): doit1(1, 0): They are within +/- 1, do something else doit1(1, 1): They are equal, do something They are within +/- 1, do something else doit1(1, 2): They are within +/- 1, do something else doit1(1, 3): doit1(Inf, Inf): They are equal, do something ----- doit2(1, -1): doit2(1, 0): They are within +/- 1, do something else doit2(1, 1): They are equal, do something doit2(1, 2): They are within +/- 1, do something else doit2(1, 3): doit2(Inf, Inf): They are equal, do something ----- doit3(1, -1): doit3(1, 0): They are within +/- 1, do something else doit3(1, 1): They are within +/- 1, do something else doit3(1, 2): They are within +/- 1, do something else doit3(1, 3): doit3(Inf, Inf): They are equal, do something ----- doit4(1, -1): doit4(1, 0): They are within +/- 1, do something else doit4(1, 1): They are equal, do something They are within +/- 1, do something else doit4(1, 2): They are within +/- 1, do something else doit4(1, 3): doit4(Inf, Inf):
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: IF condition with a range (updated)
by tobyink (Canon) on Jul 17, 2018 at 10:10 UTC | |
by syphilis (Archbishop) on Jul 17, 2018 at 10:34 UTC | |
by tobyink (Canon) on Jul 17, 2018 at 11:38 UTC | |
by syphilis (Archbishop) on Jul 17, 2018 at 13:25 UTC |