Hi markdavis87,
this is not really sorting but really counting the number of distinct entries and then sorting the counts. The easiest way is to store your lines an a hash, with the full line being the key and the count the value. Assuming your lines are stored in the @data array, you could do this:
Then you only need to sort on line size and count. And you're done.my %count_hash; for my $line (@data) { $count_hash{$line} ++; }
Edit 17:39: To do the sort, something like this should probably work (untested):
This is supposed to sort the hash content in ascending order of line lengths and descending order of counts.my @sorted_data = sort { length $a <=> length $b || $count_hash{b} <=> + $count_hash{$a} } keys %count_hash;
Edit 2, 18:30: small typo on the sorting above statement. It should be:
(I had $count_hash{b} instead of $count_hash{$b}.)my @sorted_data = sort { length $a <=> length $b || $count_hash{$b} <= +> $count_hash{$a} } keys %count_hash;
In reply to Re: String sorting in Perl
by Laurent_R
in thread String sorting in Perl
by markdavis87
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |