diff --git a/bin/look b/bin/look index 994e7a1a..1cbf3c20 100755 --- a/bin/look +++ b/bin/look @@ -16,20 +16,24 @@ License: perl use strict; use locale; + +use File::Basename qw(basename); +use Getopt::Std qw(getopts); use Search::Dict; -END { - close STDOUT || die "$0: can't close stdout: $!\n"; - $? = 1 if $? == 255; # from die -} +use constant EX_SUCCESS => 0; +use constant EX_FAILURE => 1; + +my $Program = basename($0); sub usage { - warn "$0: @_\n" if @_; - die "usage: $0 [-df] string [file ...]\n"; + warn "usage: $Program [-df] string [file]\n"; + exit EX_FAILURE; } my ( @dicts, # file list + $filearg, # optional file argument $search, # the string to look for %opt, # option hash $opened, # did we ever open something? @@ -37,16 +41,7 @@ my ( $def_dict, # did we use the default dict list? ); -@opt{ qw/d f/ } = (0, 0); - -while ($ARGV[0] =~ /^-/) { - $ARGV[0] =~ s/^-//; - for my $flag (split(//,$ARGV[0])) { - usage("unknown flag: `$flag'") unless 'df' =~ /\Q$flag/; - warn "$0: `$flag' flag already set\n" if $opt{$flag}++; - } - shift; -} +getopts('df', \%opt) or usage(); @dicts = qw( /usr/dict/words @@ -56,9 +51,18 @@ while ($ARGV[0] =~ /^-/) { $opened = $found = 0; $search = shift; - +if (!defined($search)) { + warn "$Program: missing search pattern\n"; + usage(); +} +$filearg = shift; if (@ARGV) { - @dicts = @ARGV; + warn "$Program: extra argument: '$ARGV[0]'\n"; + usage(); +} + +if (defined $filearg) { + @dicts = ($filearg); $def_dict = 0; } else { @opt{ qw/d f/ } = (1, 1); @@ -68,9 +72,12 @@ if (@ARGV) { $search = squish($search); FILE: for my $file (@dicts) { - + if (-d $file) { + warn "$Program: '$file' is a directory\n"; + next FILE; + } unless (open(DICT, '<', $file)) { - warn "$0: can't open $file: $!\n" unless $def_dict; + warn "$Program: can't open '$file': $!\n" unless $def_dict; next FILE; } @@ -89,7 +96,10 @@ LINE: last LINE; } } - close(DICT) || die "can't close $file: $!"; + if (!close(DICT)) { + warn "$Program: can't close '$file': $!\n"; + exit EX_FAILURE; + } last FILE; } @@ -99,7 +109,7 @@ if ($opened == 0) { exit 2; } -exit($found == 0 ? 1 : 0); +exit($found == 0 ? EX_FAILURE : EX_SUCCESS); sub squish { my $str = shift; @@ -117,7 +127,7 @@ look - find lines in a sorted list =head1 SYNOPSIS -look [ -df ] I [ I ... ] + look [-df] string [file] =head1 DESCRIPTION