diff --git a/bin/arithmetic b/bin/arithmetic index 006d46db..de099782 100755 --- a/bin/arithmetic +++ b/bin/arithmetic @@ -15,61 +15,38 @@ License: perl use strict; use integer; -my ($VERSION) = '1.2'; - -my $warnings = 0; - -# Print a usuage message on a unknown option. -# Requires my patch to Getopt::Std of 25 Feb 1999. -$SIG {__WARN__} = sub { - if (substr ($_ [0], 0, 14) eq "Unknown option") {die "Usage"}; - require File::Basename; - $0 = File::Basename::basename ($0); - $warnings = 1; - warn "$0: @_"; -}; - -$SIG {__DIE__} = sub { - require File::Basename; - $0 = File::Basename::basename ($0); - if (substr ($_ [0], 0, 5) eq "Usage") { - die < operators. -# r => range -my $operators = "+"; -my $range = 10; -while (@ARGV > 1) { - my $opt = shift; - if ($opt eq '-o') { - $operators = shift; - die "Usage" if $operators =~ m{[^-x+/]}; - next; - } - if ($opt eq '-r') { - $range = shift; - die "Usage" if $range =~ /\D/; - next; - } - die "Usage"; -} +use File::Basename qw(basename); +use Getopt::Std qw(getopts); + +use constant EX_SUCCESS => 0; +use constant EX_FAILURE => 1; + +my $Program = basename($0); +my ($VERSION) = '1.3'; +my %opt; +getopts('o:r:', \%opt) or usage(); +my $operators = '+'; +if (defined $opt{'o'}) { + usage() if ($opt{'o'} =~ m{[^-x+/]}); + $operators = $opt{'o'}; +} +my $range = 10; +if (defined $opt{'r'}) { + usage() if ($range !~ m/\A[0-9]+\Z/); + $range = $opt{'r'}; +} # Special case the range of 0. Since the right operator can only be 0, # division should be disallowed. die() if division was the only possible # operator. There will be nothing left. if ($range == 0) { $operators =~ s{/+}{}g; - die "division by 0 is not allowed\n" unless $operators; + unless ($operators) { + warn "$Program: division by 0 is not allowed\n"; + exit EX_FAILURE; + } } - -die "Usage" if @ARGV; +usage() if @ARGV; # Play the game! my $start = time; @@ -162,7 +139,13 @@ sub report { print "\nYou had $correct answers correct, out of $questions. ", "It took you $time.\n"; - exit $warnings; + exit EX_SUCCESS; +} + +sub usage { + warn "$Program (Perl games) $VERSION\n"; + warn "usage: $Program [-o +-x/] [-r range]\n"; + exit EX_FAILURE; } __END__