Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^5: String sorting in Perl

by Laurent_R (Prior)
on Jun 04, 2014 at 18:47 UTC ( #1088720=note: print w/ replies, xml ) Need Help??


in reply to Re^4: String sorting in Perl
in thread String sorting in Perl

Yes, quite easy. For example:

for my $line (@sorted_data) { print "$line \t $hash_count{$line} \n"; }
or:
print map {"$_ \t $hash_count{$_} \n"} @sorted_data;


Comment on Re^5: String sorting in Perl
Select or Download Code
Re^6: String sorting in Perl
by markdavis87 (Novice) on Jun 04, 2014 at 18:54 UTC

    Thanks! I think it should be "count_hash" instead of "hash_count", though. Before I read your post, I worked out this solution:

    #!/usr/bin/perl -w use strict; my $file = "path to my file"; open (FH, "< $file") or die "Can't open $file for read: $!"; my @data = <FH>; close FH or die "Cannot close $file: $!"; my %count_hash; for my $line (@data) { $count_hash{$line} ++; } for my $line (sort { length $a <=> length $b || $count_hash{$b} <=> $c +ount_hash{$a}} keys %count_hash) { print "$line\t$count_hash{$line}\n"; }

    The only thing I see is that it seems to carry over the line break with each line, so the count ends up being on a new line, tabbed over. Is there a way to have it look for a line break and remove it before it prints>

      Change the last lines to:
      for my $line (sort { length $a <=> length $b || $count_hash{$b} <=> $c +ount_hash{$a}} keys %count_hash) { chomp $line; print "$line\t$count_hash{$line}\n"; }
      (Or you also could chomp the data before.)

        Haha, that's exactly what I did before I read your post. Thanks for all the help! I really appreciate it.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1088720]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2015-07-04 00:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (57 votes), past polls