--------------------------------------------------------------------
4.63: How do I reset an each() operation part-way through?
(contributed by brian d foy)
You can use the "keys" or "values" functions to reset "each". To simply
reset the iterator used by "each" without doing anything else, use one
of them in void context:
keys %hash; # resets iterator, nothing else.
values %hash; # resets iterator, nothing else.
See the documentation for "each" in perlfunc.
--------------------------------------------------------------------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
I hope this doesnt't sound like a d'oh moment, but am I being lead to
believe that all these years I have been using the following:
foreach $temp (keys(%in))
{
print $in{$temp};
}
I could have been using this instead:
foreach $temp (values(%in))
{
print $temp;
}
Bill H
In this case, yes. The two loops do the same thing. I've found that in
practice I usually need the key for some reason and end up using the
first form. It's a guilty pleasure when I can iterate over values()
instead. ;)
There is also a third option that's occasionally useful:
while (my ($k, $v) = each %hash) {
print "$k => $v\n";
}
-mjc