Skip to content

Commit

Permalink
Merge pull request #274 from mknos/look-1file
Browse files Browse the repository at this point in the history
look: reject multiple file arguments
  • Loading branch information
briandfoy authored Sep 30, 2023
2 parents b91d121 + 7906099 commit ac556f7
Showing 1 changed file with 33 additions and 23 deletions.
56 changes: 33 additions & 23 deletions bin/look
Original file line number Diff line number Diff line change
Expand Up @@ -16,37 +16,32 @@ 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?
$found, # did we ever find something?
$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
Expand All @@ -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);
Expand All @@ -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;
}

Expand All @@ -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;
}

Expand All @@ -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;
Expand All @@ -117,7 +127,7 @@ look - find lines in a sorted list
=head1 SYNOPSIS
look [ -df ] I<string> [ I<file> ... ]
look [-df] string [file]
=head1 DESCRIPTION
Expand Down

0 comments on commit ac556f7

Please sign in to comment.