in reply to String sorting in Perl
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;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: String sorting in Perl
by Limbic~Region (Chancellor) on Jun 04, 2014 at 17:38 UTC | |
by Laurent_R (Canon) on Jun 04, 2014 at 17:48 UTC | |
by Limbic~Region (Chancellor) on Jun 04, 2014 at 18:06 UTC | |
Re^2: String sorting in Perl
by markdavis87 (Novice) on Jun 04, 2014 at 18:14 UTC | |
Re^2: String sorting in Perl
by markdavis87 (Novice) on Jun 04, 2014 at 18:23 UTC | |
by Laurent_R (Canon) on Jun 04, 2014 at 18:26 UTC | |
by markdavis87 (Novice) on Jun 04, 2014 at 18:29 UTC | |
by Laurent_R (Canon) on Jun 04, 2014 at 18:47 UTC | |
by markdavis87 (Novice) on Jun 04, 2014 at 18:54 UTC | |
| |
by markdavis87 (Novice) on Jun 04, 2014 at 19:06 UTC | |
Re^2: String sorting in Perl
by Anonymous Monk on Jun 04, 2014 at 18:02 UTC |