in reply to Re: File ext number
in thread File ext number

Here is a more verbose solution and assumes that your files are being stored in an array.

Not really.

for my $file (sort grep -f, readdir $dh)
works just as well as
for my $file (sort @files)

my $num = 1; is useless and detrimental. It reminds me of

use constant TWO => 2;

when one should rather be doing

use constant NUM_EYES => 2;

There's a point where constants become a hindrance.

my $num = 1; if (exists $extensions{$key}) { $extensions{$key} += $num; } else { $extensions{$key} = $num; }
should be
if (defined $extensions{$key}) { $extensions{$key} += 1; } else { $extensions{$key} = 1; }
But why not just use ++? It even works great at incrementing previously undefined values.
++$extensions{$key};

Replies are listed 'Best First'.
Re^3: File ext number
by Lady_Aleena (Priest) on Mar 20, 2010 at 03:54 UTC

    I had made the assumption that the files were being stored in an array. I hadn't thought of any other way to get the file list from the directory outside of File::Find which creates an array.

    I really overdid counting the instances of each file extension. I had thought of incrementation, but I hadn't thought to use it to define a previously undefined variable. So, the code below is better without the constant my $num = 1;.

    my %extensions; for my $file (sort @files) { my @split = split(/\./,$file); my $key = $split[1]; ++$extensions{$key}; } while (my ($key,$value) = each %extensions) { print $key." - ".$value."\n"; }
    Have a nice day!
    Lady Aleena