From 7acb2a8d670862371076494ad7d5d39b4009956f Mon Sep 17 00:00:00 2001 From: Michael Mikonos <127171689+mknos@users.noreply.github.com> Date: Fri, 27 Sep 2024 17:48:45 +0800 Subject: [PATCH] grep: simplify parse_args() * 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) --- bin/grep | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/bin/grep b/bin/grep index 4afe175f..955cb23a 100755 --- a/bin/grep +++ b/bin/grep @@ -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'}; @@ -255,9 +249,9 @@ sub parse_args { $opt{P} && ( $/ = eval(qq("$opt{P}")) ); # for -P '%%\n' $opt{w} && ( @patterns = map { '(?:\b|(?!\w))' . $_ . '(?:\b|(?{'s'} ) { warn "$Me: can't opendir $file: $!\n"; $Errors++; @@ -323,11 +318,11 @@ FILE: while ( defined( $file = shift(@_) ) ) { 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 ) }