in reply to Hash sorting

You're handling the hash wrong. Try this:
my %calhash; my $key = ""; my $value = ""; while (<OUTFILE>) { chomp; my ($key, $value) = split(/;/, $_); $calhash{$key} = $value; } foreach $key (sort {$b cmp $a} keys %calhash) { print TESTFILE "$key;$calhash{$key}\n"; }

Update: Dunno what sorting algorithm he wants. I assumed reverse alphanumeric like he typed. I didn't have enough information to change the sorting logic...

buckaduck

Replies are listed 'Best First'.
Re: Re: Hash sorting
by derby (Abbot) on Mar 13, 2002 at 18:23 UTC
    Good call but doesn't he want to sort by the number of clients and not the client name?

    foreach $key ( sort{ $calhash{$b} <=> $calhash{$a} } keys %calhash ) {

    -derby

    Yahoo! 100th post.

Re: Re: Hash sorting
by jamen (Initiate) on Mar 15, 2002 at 16:25 UTC
    my %calhash; my $key = ""; my $value = ""; while (<OUTFILE>) { chomp; my ($key, $value) = split(/;/, $_); $calhash{$key} = $value; } foreach $key (sort {$b cmp $a} keys %calhash) { print TESTFILE "$key;$calhash{$key}\n"; }
    Thank you!!!! That worked!!! Why was the chomp placed before the split?
    On this line $calhash{$key} = $value what is that saying?
    Just trying to learn why I was off and my logic for it. Once again, thank you!
    Ben
      (1) the chomp was placed before the split so that the value being split didn't have a newline. With the chomp afterwards, you're removing in the newline from $_, not $value (which was populated before the chomp)
      (2) in your orginal code the statement read "put the value of $key into hash at key '$key'", rather than as the updated code has it. "put the value of $value into the hash at key '$key'.

      rdfield

      1. The chomp comes before the split so that you remove carriage-returns from each line before you split it into $key and $value. If you don't do this, each $value will retain a trailing carriage return. Chomping the line after the split is pointless in this case, since you don't use the implicit variable $_ again.

      2. $calhash{$key} is the value in %calhash which the key $key points to. I'm assigning it a new value $value. Later, if I want the key and value again (like in the printing loop), I'll refer to $key and $calhash{$key}.

      The syntax for Variable Names is covered in perldata of the perl documentation.

      buckaduck