On Jul 2, 9:20 am, [EMAIL PROTECTED] wrote: > i had a problem with hashes...can any one help > > ihad a hash with keys and values... > > # DEFINE A HASH > %coins = ( "12345" , 91, > "987658" ,35.5, > "wer123", 99.8, > "456hn",56.4, > "34567",78.9, > "00000",99.9, > "yui345",45.4); > > # LOOP THROUGH IT > foreach $value (sort {$coins{$a} cmp $coins{$b} } keys %coins)
You're iterating through a sorted list of keys, but you're calling each one of those keys "$value". That's bound to confuse a future reader of your code (which may end up being yourself) > { > print "<$value---> $coins{$value}>\n"; > > } > > so now is hash is printing in sorted order....like > <987658---> 35.5> > <yui345---> 45.4> > <456hn---> 56.4> > <34567---> 78.9> > <12345---> 91> > <wer123---> 99.8> > <00000---> 99.9> > > wat i need is for ex if i gave 34567 it has to tell the position of > the hash 4th position... You're asking for Perl to tell you something that's not true. 34567 is NOT at the "fourth position". It's not at any such numbered position. 34567 is a key whose value in %coins is 78.9. > how can i do that..... Sounds to me like what you really want is to get a list of keys in some particular order (like the one you imposed in your foreach loop above), find the position of one particular key in the sorted list of keys. That's not the same thing as finding the position of one particular key in the hash itself. Here's one way: my $i = 0; foreach my $key (sort {$coins{$a} cmp $coins{$b} } keys %coins) { $i++; print "$key is at position $i\n" if $key eq '34567'; } Here's another: my $i = 0; my %position_of = map { $_ => ++$i } sort {$coins{$a} cmp $coins{$b} } keys %coins; print "Position of '34567' is $position_of {34567}\n"; Hope this helps, Paul Lalli -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/