in reply to file ext counter.

This line:
use warnings; use strict; use File::Find; my %hash; my @temp; my $dir = shift @ARGV; die "Give me a directory to search\n" unless (-d "$dir"); File::Find::find (\&wanted,"$dir"); print "-"x20,"\n"; foreach my $key (sort keys %hash) { print $key, "\t:\t",$hash{$key},"\n"; } sub wanted { # don't attempt to read a directory. return if (-d $_); my $fname = $File::Find::name; @temp = split(/[\/\\]/, $fname); $fname = $temp[-1]; # Make sure there is an extension. We check for a # trailing period even though on Win32 it shouldn't happen if (($fname =~ /\./) && !($fname =~ /\.$/)) { $fname = lc($fname); @temp= split(/\./, $fname); $hash{$temp[-1]}++; } else { $hash{"no ext"}++; } }

Update:
I Changed a few more things around. I went right for the filename since a "." in a directory could mess things up as well.
$array[-1] so that we don't have troubles with files like "blah.txt.sh".
And we now account for no extension at all.
This code could make use of File::Basename as well.

Replies are listed 'Best First'.
Re: Re: file ext counter.
by boo_radley (Parson) on Nov 22, 2000 at 21:25 UTC
    ah, I see why you'd want to use  $hash{@temp[-1]}++ but this exhibits bad behavior for files with no extention at all! update

    your

    if (($fname =~ /\./) && !($fname =~ /\.$/)) { $fname = lc($fname); @temp= split(/\./, $fname); $hash{$temp[-1]}++; } else { $hash{"no ext"}++; }
    seems a little clumsy. consider
    if ($#temp >0) {$hash{@temp[-1]}++} else {$hash{""}++}
    which sees if there's more than 1 bucket in @temp. If there is, we know the lastmost one's the extention. If there isn't we know the filename has no extention. in fact, I think this can be shortened to <code> if ($#temp) <code> but that's not a big deal. I kept the hash named "" for the highly special case of a file, e.g. "foo.no ext"