I can't figure out why the print statement keeps printing the same word as a key value.
The short answer is: Because that is what you asked it to do:)
A slightly longer and hopefully helpful answer is that the keys function returns the keys from the hash. If you want to print the values from the hash you have two options. You can either use the key to retrieve the value from the hash
%hash = qw/a 1 b 2 c 3 d 4 e 5/; for $key (keys %hash) { print 'Key:', $key, '=', $hash{ $key }, "\n" } Key: e = 5 Key: c = 3 Key: a = 1 Key: b = 2 Key: d = 4
This is often done when you want to display the keys and the value as above, or perhaps when you want the values ordered by the keys.
%hash = qw/a 5 b 4 c 3 d 2 e 1/; for $key (sort keys %hash) { print $hash{ $key }, "\n" } 5 4 3 2 1
Here, the keys were sort ascending, but the values come out descending because thats the way they are associated.
However, if you just want to print out the values and don't care about their order, or you want to order them by their own value, not that of their associated keys then you can use the values function instead.
perl> %hash = qw/a 5 b 4 c 3 d 2 e 1/; for $val (values %hash) { print $val, "\n" } 1 3 5 4 2 for $val ( sort values %hash ) { print $val, "\n" } 1 2 3 4 5
HTH.
In reply to Re: Re: Re: File write
by BrowserUk
in thread File write
by perl_seeker
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |