From 425f0427df443ab81a167e79a6e88804310ef62f Mon Sep 17 00:00:00 2001 From: Michael Mikonos <127171689+mknos@users.noreply.github.com> Date: Tue, 1 Oct 2024 20:10:21 +0800 Subject: [PATCH] what: reduce code nesting * Rewrite printWhat() function with fewer levels of nesting * Input loop is restructured to no longer require $done variable * Replace if-regex-matches loop with grep() * I verified that the output, with and without -s flag, matches the output of an older commit when running command across all of /usr/bin on my Linux system * I also ran a diff of output between -s and not-s to show that -s only lists one match per input file --- bin/what | 56 +++++++++++++++++++++++--------------------------------- 1 file changed, 23 insertions(+), 33 deletions(-) diff --git a/bin/what b/bin/what index 161d7847..cfa04f7a 100755 --- a/bin/what +++ b/bin/what @@ -30,45 +30,35 @@ for my $file (@ARGV) #### pass in file handle, file name, and whether to stop printing after 1st "what" sub printWhat { - my $file_handle = $_[0]; - my $file_name = $_[1]; - my $stop_flag = $_[2]; + my $file_handle = shift; + my $file_name = shift; + my $stop_flag = shift; + my $line; print "$file_name:\n" if $file_name ne ""; - my $done = 0; - while (! $done) + while (defined($line = <$file_handle>)) { - my $line = <$file_handle>; - if (defined $line) + next unless $line =~ m/\@\(#\)/; + + if ((! $stop_flag) && ($line =~ /\0/)) ## there may be more than 1 in here { - if ($line =~ /\@\(#\)/) + my @F = split(/\0/, $line); + my @match = grep { m/\@\(#\)/ } @F; + for my $f (@match) { - if ((! $stop_flag) && ($line =~ /\0/)) ## there may be more than 1 in here - { - my @F = split(/\0/,$line); - for my $f (@F) - { - last if $done; - if ($f =~ /\@\(#\)/) - { - $f =~ s|.*\@\(#\)||; - $f =~ s|[">\0\\].*||; ##BSD spec says print to 1st " > \ or null - chomp $f; - print " $f\n"; - $done = 1 if $stop_flag; - } - } - } - else - { - $line =~ s|.*\@\(#\)||; - $line =~ s|[">\0\\].*||; ##BSD spec says print to 1st " > \ or null - chomp $line; - print " $line\n"; - } - $done = 1 if $stop_flag; + $f =~ s|.*\@\(#\)||; + $f =~ s|[">\0\\].*||; ##BSD spec says print to 1st " > \ or null + chomp $f; + print " $f\n"; } } - else { $done = 1; } + else + { + $line =~ s|.*\@\(#\)||; + $line =~ s|[">\0\\].*||; ##BSD spec says print to 1st " > \ or null + chomp $line; + print " $line\n"; + } + last if $stop_flag; } }