|
Posted by Dave Saville on June 12, 2008, 5:18 am
Please log in for more thread options
wrote:
>
> > On Fri, 30 May 2008 13:11:22 UTC, Gunnar Hjalmarsson
> >
> > > dn.perl@gmail.com wrote:
> > > > I want to sort a hash. The hash contains a list of cities and their
> > > > temperature
> > >
> > > Well, I'd rather say it contains three hash references.
> > >
> > > This is one sensible way to sort that data structure:
> > >
> > > foreach my $state ( sort keys %hash ) {
> > > print "State: $state\n";
> > > foreach my $city ( sort { $a cmp $b } keys %{ $hash } ) {
> > > print "$city = $hash\n";
> > > }
> > > print "\n";
> > > }
> >
> >
> > Sorry to jump in with another question but I have a very similar
> > problem. I am processing a consolidated apache2 logfile. I have
> > multiple virtual hosts. All I care about are the site, the page
> > served, a counter and the date.
> >
> > So my hash looks like $urls Beyond that I have a counter
> > and date thus:
> > $urls[0]++; # count
> > $urls[1] = $date;
> >
> > This works fine and I can list by site the page, count and date.
> >
> > foreach $site ( keys %urls)
> > {
> > foreach my $url (keys %})
> > {
> > print "$site $url $urls[0] $urls[1]\n";
> > }
> > }
> >
> > Putting a sort into the url loop gives me the results sorted by page
> > as expected. What I cannot figure out is how to do it by count and by
> > date.
> >
> > I have tried various ideas I found by google but they all tend to be
> > similar to this
> >
> > sub by_count
> > {
> > $urls[0] <=> $urls[0] or $a cmp $b;
> > }
> >
> > But this throws lots of "Use of uninitialized value....." errors on
> > that line and in doing so gets the wrong pages attributed to a site. I
> > have tried with yet another hash on the end with count & date keys
> > instead of the array, but it does not help.
> >
> > I would be grateful for any pointers.
>
> Are you trying to sort all of your records at once, regardless of site?
> You can't do that with a simple sort. If you just want to sort the data
> by site, here is an example:
<snip>
Thanks Jim. No, one site's ouput needs sorting by date and the rest by
count. I have found the problem, reported in another reply, but
basically my version of perl treats
sort { some sort statement} keys %hash
and
sort by_value keys %hash
where by_value contains the exact same sort statement differently.
--
Regards
Dave Saville
NB Remove nospam. for good email address
|