Get an arbitrary hash key, quickly.

N

nolo contendere

I think the link to plover that Ben Morrow posted already did that.
It isn't actually weird, I just treat as weird because it isn't documented
and so could in theory do something different in other versions.

Well, OK, it is weird, because the docs "If any part of LIST is an array"
but it seems that, to get the behavior shown in the plover link, the
entirety of the LIST has to be an array.  if you do something like:

foreach ("foo",@x) {

Then it appears, at least on my version, that it does in fact take a
snapshot of @x (more properly, a snapshot of the addresses to the elements
in @x) and any splices made into it during the loop have no effect on the
iteration.

thanks Xho, I'll check out the plover site more thoroughly.
 
K

kj

Xho, why do you like this

In said:
while (keys %hash) {
foreach my $to_do (keys %hash) {
delete $hash{$to_do};
## do stuff with $to_do, which might
# make new entries in %hash
}
}

better than your original
while (%hash) { # does not reset iterator
my $to_do=each %hash;
next unless defined $to_do; # not a real hash key,
# signals end of iterator
## do stuff with $to_do, which might make new entries in %hash
};

?

kynn
 
X

xhoster

kj said:
Xho, why do you like this



better than your original


?

I'm not keen on using "scalar %hash", as it is more esoteric than
"scalar keys %hash". And using the next to cause they "each" to reboot
when it delivers an undefined value is more subtle than I care for.

On the other hand, at this long remove, I am kind of looking kindly on my
original code. It looks abnormal, which advertises the fact that it
is abnormal and should be tinkered with with caution.

Xho

--
-------------------- http://NewsReader.Com/ --------------------
The costs of publication of this article were defrayed in part by the
payment of page charges. This article must therefore be hereby marked
advertisement in accordance with 18 U.S.C. Section 1734 solely to indicate
this fact.
 
K

kj

In said:
I'm not keen on using "scalar %hash", as it is more esoteric than
"scalar keys %hash". And using the next to cause they "each" to reboot
when it delivers an undefined value is more subtle than I care for.

Still, using foreach in the inner loop is unnecessary use of memory.
What's wrong with

while ( keys %hash ) {
while ( my $to_do = each %hash ) {
delete $hash{ $to_do };
# etc.
}
}

?

Or perhaps this expresses the intentions more clearly:

{
while ( my $to_do = each %hash ) {
delete $hash{ $to_do };
# etc.
}

redo if keys %hash;
}

kynn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top