in reply to Cleaning up unused subroutines

Oneliner that count occurrences of sub names in a file:
FILE=foo.pl ; for i in `cat $FILE |grep -E "^sub " | sed 's/^sub.\([A- +Za-z0-9_]*\).*$/\1/'` ; do c=`grep -c $i $FILE` ; echo $c $i ; done | + sort -rn

Replies are listed 'Best First'.
Re^2: Cleaning up unused subroutines
by hippo (Archbishop) on Sep 19, 2018 at 08:58 UTC

    Hello neszt76 and welcome to PerlMonks. We use Perl here.

    perl -nE '$f.=$_}{$t{$_}=()=$f=~/\Q$_/g for $f=~/^sub\s+(\w+)/gm;say " +$t{$_} $_" for sort {$t{$b} <=> $t{$a}} keys %t;' $FILE

    This uses precisely* the same logic as your shell loop above (and therefore has the same algorithmic flaws). Nonetheless, advantages of the Perl approach include:

    • No multiple forks to grep (one for each sub found)
    • Works on multiple input files at once just by appending more to the argument list
    • Works on systems without sh, sed, grep, et al.
    • Looks like line noise so your cow-orkers will be amazed you can read it let alone write it
    • No UUOCA ;-)

    Enjoy.

    *Not precisely: there's one trivial fix to avoid lines which start with eg. "submarine".