in reply to Re: Hash sorting
in thread Hash sorting

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

Replies are listed 'Best First'.
Re: Re: Re: Hash sorting
by rdfield (Priest) on Mar 15, 2002 at 16:32 UTC
    (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

Re: Re: Re: Hash sorting
by buckaduck (Chaplain) on Mar 15, 2002 at 16:53 UTC
    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