Hello adriang,
I realise your code snippet is just for illustration; still, it may be instructive to note its various problems:
Compile error: the second closing parenthesis is missing.
Logic error: in scalar context the keys function returns the number of keys in the hash, not the keys themselves. You need a for loop here:
for my $key (keys %hash) {
Logic error: since you want to exit the loop when a certain key is reached, the behaviour of the code depends on the order in which the keys are returned; but this order is “apparently random” (keys). To get deterministic behaviour, you need to sort the keys. For example:
for my $key (sort keys %hash) {
Compile error: if you’re running under use strict; (and you should be!), you will see this error message:
Global symbol "$key" requires explicit package name at ...
You could fix this1 by declaring my $key; before the loop, but it’s better style to restrict the scope of this lexical variable:
for my $key (sort keys %hash) { if ($key eq $verb) { $hash{$key} = $verb; last; } }
Update (Aug 23):
1That is, you could fix the error message. But the code still wouldn’t work correctly, because $key is a temporary alias within the foreach loop (see “alias” in perlglossary), and it reverts to its pre-loop value when the loop ends.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: while loop question
by Athanasius
in thread while loop question
by adriang
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |