K
ko
I was looking for an efficient way to find the largest key (assuming all
numeric keys) in a *large* hash and found an excellent solution here
(sorry for the long link):
http://groups.google.com/[email protected]#link5
the relevant code:
foreach ($max = each %hash;
defined ($a = each %hash);
$max = $a if $a > $max) {}
Took me a while to figure it out - most of the time you see 'foreach'
being shortened to 'for' instead of the other way around.
Anyway, there are two things I can't figure out.
1. If you're including the strict and warnings pragmas, why is it that
you can get away with not declaring $a? I thought defined() might have
something to do with it, but the docs only say that when used on a hash
element it tells you whether the value is defined.
2. Is defined() necessary in the condition? The assignment of each key
to $a returns true. I think there was a reference in the thread to why
defined is used, but I didn't understand the explanation, so I'm not sure.
For anyone who might suggest sort() or iterating with keys() to
accomplish the task, please follow the link above for explanations to
why this method is more efficient.
Thanks in advance - keith
numeric keys) in a *large* hash and found an excellent solution here
(sorry for the long link):
http://groups.google.com/[email protected]#link5
the relevant code:
foreach ($max = each %hash;
defined ($a = each %hash);
$max = $a if $a > $max) {}
Took me a while to figure it out - most of the time you see 'foreach'
being shortened to 'for' instead of the other way around.
Anyway, there are two things I can't figure out.
1. If you're including the strict and warnings pragmas, why is it that
you can get away with not declaring $a? I thought defined() might have
something to do with it, but the docs only say that when used on a hash
element it tells you whether the value is defined.
2. Is defined() necessary in the condition? The assignment of each key
to $a returns true. I think there was a reference in the thread to why
defined is used, but I didn't understand the explanation, so I'm not sure.
For anyone who might suggest sort() or iterating with keys() to
accomplish the task, please follow the link above for explanations to
why this method is more efficient.
Thanks in advance - keith