Skip to content

Commit

Permalink
grep: simplify parse_args()
Browse files Browse the repository at this point in the history
* Remove the need for variables $zeros and $nulls for processing opt-hash before calling getopts()
* opt-e is guarded against undef by length() check
* opt-p and opt-P are used in a print() statement so init these to empty string directly
* When overriding opt-1, opt-g and opt-c, use logical operator instead of addition operator, which would warn for undef operand
* As done previously with filehandles, convert directory handle DIR to a my-variable (this is used for for grep -r)
  • Loading branch information
mknos authored Sep 27, 2024
1 parent 8bdcd74 commit 7acb2a8
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions bin/grep
Original file line number Diff line number Diff line change
Expand Up @@ -124,20 +124,14 @@ EOF
###################################

sub parse_args {
my ( $zeros, $nulls, %opt, $pattern, @patterns, $match_code );
my ( $SO, $SE );
my (%opt, $pattern, @patterns, $match_code, $SO, $SE);

if ( defined( $_ = $ENV{'GREP_OPTIONS'} ) ) {
s/^([^\-])/-$1/; # add leading - if missing
unshift @ARGV, $_;
}

$zeros = 'inCwxvghHLlut'; # options to init to 0 (prevent warnings)
$nulls = 'epP'; # options to init to "" (prevent warnings)

@opt{ split //, $zeros } = (0) x length($zeros);
@opt{ split //, $nulls } = ('') x length($nulls);

$opt{'p'} = $opt{'P'} = ''; # argument to print()
getopts('inCcwsxvHhe:f:Ll1gurtpP:aqTF', \%opt) or usage();

$opt->{'l'} = 0 if $opt->{'L'};
Expand Down Expand Up @@ -255,9 +249,9 @@ sub parse_args {
$opt{P} && ( $/ = eval(qq("$opt{P}")) ); # for -P '%%\n'
$opt{w} && ( @patterns = map { '(?:\b|(?!\w))' . $_ . '(?:\b|(?<!\w))' } @patterns );
$opt{'x'} && ( @patterns = map {"^$_\$"} @patterns );
$opt{1} += $opt{l}; # that's a one and an ell
$opt{'g'} += $opt{'u'};
$opt{c} += $opt{C};
$opt{'1'} ||= $opt{'l'}; # that's a one and an ell
$opt{'g'} ||= $opt{'u'};
$opt{'c'} ||= $opt{'C'};

foreach (@patterns) {s(/)(\\/)g}

Expand Down Expand Up @@ -315,19 +309,20 @@ FILE: while ( defined( $file = shift(@_) ) ) {
warn qq($Me: "$file" is a directory\n);
next FILE;
}
unless ( opendir( DIR, $file ) ) {
my $dh;
unless (opendir $dh, $file) {
unless ( $opt->{'s'} ) {
warn "$Me: can't opendir $file: $!\n";
$Errors++;
}
next FILE;
}
@list = ();
for ( readdir(DIR) ) {
for (readdir $dh) {
next if $_ eq '.' or $_ eq '..';
push @list, File::Spec->catfile($file, $_);
}
closedir(DIR);
closedir $dh;
if ( $opt->{t} ) {
my (@dates);
for (@list) { push( @dates, -M ) }
Expand Down

0 comments on commit 7acb2a8

Please sign in to comment.