#!/usr/bin/perl

use 5.038.2;

unless (@ARGV){
    say "";
    say "Usage: $0 <scriptperl1> <scriptperl2> ...";
    say "";
    say "This script count scalar and list uses in a script";
    say "and reports only one use of var name.";
    say "";
    exit -1;
}

for ( @ARGV ){
    next unless (-e $_ && -T $_);
    
    my $filename = $_;
    say "$filename:";
    
    my @content;
    open my $in, '<', $filename or warn $!;
    @content = <$in>;
    close $in;
    chomp @content;

    next unless ($content[0] =~ /perl/);

    my $max = 0;

    my $linecount = 1;
    my %hash;
    for my $line ( @content ){
	
	while ($line){          # sí o sí
	
	    if ( $line =~ s/([\$|\@|\%])(\w+)// ) {    # doy por supuesto que cuando tengo $ o @ o % la cosa está hecha. No.
		# Pueden estar en strings o regex, o usarse otra vez pero sólo para asignar algo y no usarlo. Falso negativo.
		last unless ($1 && $2 && length($2) >= 1);
		$hash{ $2 } += $linecount;
		$max = ($hash{ $2 } > $max) ? $hash{ $2 } : $max;    # maximum use 
	    }else{
		last;
	    }
	}
	
	$linecount++;
    }

    my $flags = 0;
    while (my ($key, $value) = each %hash) {
	if ($value == 1){
	    say "Suspected variable or list or hash named { $key } used only once, line number $hash{ $key }";
	    $flags++;
	}elsif ($value == $max) {
	    say "Token (scalar, list or hash) { $key } is most used per script";
	}
    }        # se pueden hacer más cosas, ya... como hacer histograma de variables. ¿Hay demanda? 
    say "\nCongrats! you score 0 in unused variables!" if ($flags == 0);
    say "";
}

exit 3;
    
__END__
  
Errores en plantilla: se comuta igual una variable escondida en un comentario :-)

