krad has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I just starting to work a problem out with an array of file names. I would like to compare the file names and find in the array the most common used names. Not sure where to start with this problem. Did think of sorting the array then comparing the index with the one below? . do you know of a modul that might help with this?

Replies are listed 'Best First'.
Re: File name compareing
by mbethke (Hermit) on Feb 09, 2012 at 21:21 UTC

    The simplest way would be to count the frequencies of all names and then take the top n of these. Loop over all the names, use each name as a hash key and as the hash value keep a counter of how often you encountered it. The value will be undefined for the first occurrence so the ++ operator correctly assumes zero instead.

    my %freqs; $freqs{$_}++ foreach(@filenames);

    Then sort by frequency, descending (compare $freqs{$b} with $freqs{$a} instead of the other way round), and take the first say 10:

    my @most_frequent = (sort { $freqs{$b} <=> $freqs{$a} } keys %freqs)[0..9];