CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
sorting a hash

 



ptyo
Novice

Sep 15, 2009, 10:52 AM

Post #1 of 4 (281 views)
sorting a hash Can't Post

Okay here is what I have now.

#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

my %hosts;




while (<STDIN>) {

next unless /^(\d+\.){3}\d+/; #skip lines that don't start with an IP address

my $host = (split(/\s/, $_))[5]; #split the lind by the space char and extract the 6th element (r-host field)

$hosts{ $host }++;
}

# sort by value and put the keys in an array
@keys = sort {$hosts{$b} <=> $hosts{$a}} keys %hosts;

# loop through array to print the has pairs ordered

foreach $key (@keys)
{
print "$key: $hosts{$key}\n";
}

#print Dumper \%hosts;



I read in a log file.. which works fine but when I added the sort by value and loop to print hash I get an

Global symbol @keys requires explici package name at log.pl line 22.

which is @keys = sort {$hosts{$b} <=> $hosts{$a}} keys %hosts;



What am I doing wrong... The hashes simply county the number of website occurences in my log and displays..



google > 23

yahoo > 2



i just want to print the hash from largest number to least to show what the most visited site is.

Thanks.


savo
User

Sep 15, 2009, 11:37 AM

Post #2 of 4 (277 views)
Re: [ptyo] sorting a hash [In reply to] Can't Post

You need to declare it add my before @keys


ptyo
Novice

Sep 16, 2009, 6:53 AM

Post #3 of 4 (271 views)
Re: [savo] sorting a hash [In reply to] Can't Post

guess I am a little confused on using my

what does it do? Is it like a namespace to where say...



my $fileName

is not the same as

$fileName



????


savo
User

Sep 16, 2009, 7:15 AM

Post #4 of 4 (268 views)
Re: [ptyo] sorting a hash [In reply to] Can't Post

You have "use strict;" at the top of your code which is good practice but means that you have to declare all variables the first time they are used. Which is handy because if you made a typo like below it would be picked up.

$var = ''hello";
print $Var ###prints nothing

use strict:
$var = ''hello";
print $Var ### gives an error.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives