Skip to content

Commit

Permalink
grep: bad filehandle passed to close() (#746)
Browse files Browse the repository at this point in the history
* When temporarily enabling warnings+diagnostics in grep I observed a warning related to FILE being used only once
* The close(FILE) statement was incorrect because the current input file is actually $fh
* The correct place to close the file was after the LINE-loop
* Technically $fh was being closed implicitly after each FILE-loop, but keep the pattern of explicitly closing it
* Style: where possible, refer to the LINE-loop when jumping from within the LINE-loop
* Also convert PATFILE into a regular "my" variable, so there are no more bareword files
  • Loading branch information
mknos authored Sep 27, 2024
1 parent e4c9d76 commit 8bdcd74
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions bin/grep
Original file line number Diff line number Diff line change
Expand Up @@ -145,19 +145,21 @@ sub parse_args {
$match_code = '';

if (defined $opt{'f'}) { # -f patfile
die("$Me: $opt{f}: is a directory\n") if ( -d $opt{f} );
open PATFILE, '<', $opt{f} or die qq($Me: Can't open '$opt{f}': $!\n);
my $path = $opt{'f'};
my $patfile;
die "$Me: $path: is a directory\n" if -d $path;
open($patfile, '<', $path) or die "$Me: Can't open '$path': $!\n";

# make sure each pattern in file is valid
while ( defined( $pattern = <PATFILE> ) ) {
while ( defined( $pattern = <$patfile> ) ) {
chomp $pattern;
unless ($no_re) {
eval { 'foo' =~ /$pattern/, 1 }
or die "$Me: $opt{f}:$.: bad pattern: $@\n";
or die "$Me: $path: $.: bad pattern: $@\n";
}
push @patterns, $pattern;
}
close PATFILE;
close $patfile;
}
else { # make sure pattern is valid
$pattern = $opt{'e'};
Expand Down Expand Up @@ -402,16 +404,17 @@ FILE: while ( defined( $file = shift(@_) ) ) {
}
if ($opt->{'l'}) {
print $name, "\n";
next FILE;
last LINE;
}
unless ($opt->{'c'}) {
print($name, ':') if $Mult;
print $opt->{n} ? "$.:" : "", $_,
( $opt->{p} || $opt->{P} ) && ( '-' x 20 ) . "\n";
}

next FILE if $opt->{'1'}; # single match per file
last LINE if $opt->{'1'}; # single match per file
}
close $fh;
}
continue {
if ($opt->{'c'}) {
Expand All @@ -421,7 +424,6 @@ FILE: while ( defined( $file = shift(@_) ) ) {
if ($opt->{'L'} && !$total) {
print $name, "\n";
}
close FILE;
}
$Grand_Total += $total;
}
Expand Down

0 comments on commit 8bdcd74

Please sign in to comment.