sort hash by values desc

Hello

I have a perl file to which i am feeding values of form

https://www.bankofamerica.com/index.jsp
https://www.airmiles.ca/servlet/ContentServer?pagename=Airmiles/Service/Login/Index&prefer_lang=E
https://www.amazon.com/gp/sign-in.html
ftp://ftp.cpan.org/
ftp://ftp.cpan.org/pub
ftp://ftp.cpan.org/usr
ftp://ftp.cpan.org/pub/misc
ftp://ftp.cpan.org/pub/unix
ftp://ftp.cpan.org/pub/CPAN
ftp://ftp.cpan.org/pub/CPAN/disclaimer.html
ftp://ftp.cpan.org/pub/CPAN/indices
ftp://ftp.cpan.org/pub/CPAN/doc
ftp://ftp.cpan.org/pub/CPAN/modules
http://www.weatheroffice.ec.gc.ca/forecast/city_e.html?bc-85&unit=i
news:comp.lang.perl.misc
news:comp.lang.perl.modules


The perl file i am using is

#!/usr/bin/perl
use warnings;
use strict;

my( %count,%count1) = ();
my @words;
my ($filename,$args,$word,$str,$temp) = " ";

$args         = scalar(@ARGV);

if($args >= 1)
{
   $filename       = $ARGV[0];
   open INFILE, "< $filename" or die "Can not open $filename : $!";
}else {  die "Error: Incorrect number of arguments \n"; }

sub hashValueAscendingNum {
   $count{$b} <=> $count{$a};
}


while(<INFILE>)
{
  chomp;
  my @word = split (/:/,$_);
  foreach $word(@word)
  {
    $count{$word[0]}++ if $word[0] =~ /^[http|https|ftp]/;
    $count1{$2}++ if $word[1] =~ /([^:]*:\/\/)?([^\/]+\.[^\/]+)/g;
  }
}


foreach $str (sort hashValueAscendingNum (keys(%count)))
{
  printf " %30s %s \n", $str, $count{$str};
}

foreach $str (sort hashValueAscendingNum (keys(%count1)))
{
  printf " %30s %s \n", $str, $count1{$str};
}

However, i am not able to sort the %count1 by values desc ? ( Getting an error and hash is not sorted properly )

Also from %count and %count1, i want to display only 2 topmost records, which is not achieved via foreach loop

please advise ...
clock_crazyAsked:
Who is Participating?
 
ozoCommented:
foreach $str ((sort { $count1{$b} <=> $count1{$a}} keys %count1)[0..1])
{
  printf " %30s %s \n", $str, $count1{$str};
}
0
 
clock_crazyAuthor Commented:
Thank you that works. I was missing the name of hash and while reviving values of hash, it always return in list.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.