Dear Jenda,

Ah, that makes a lot of sense!

I couldn't find any references to this in "Programming Perl" or the "Perl
Cookbook". It's a pretty major thing to know about, though. Eventually I
found this in PerlFaq4:

How do I reset an each() operation part-way through?
Using keys %hash in scalar context returns the number of keys in the hash
and resets the iterator associated with the hash. You may need to do this if
you use last to exit a loop early so that when you re-enter it, the hash
iterator has been reset.

Thanks,

Chris Humphries

> -----Original Message-----
> From: Jenda Krynicky [mailto:[EMAIL PROTECTED]]
> Sent: Monday, January 21, 2002 4:11 PM
> To: Christopher Humphries; 'Activeperl
> Subject: Re: A problem with hash references and while() loops?
>
>
> From:                 "Christopher Humphries"
> <[EMAIL PROTECTED]>
> > Can anyone shed light on this problem?
> >
> > I noticed some strange behaviour with a hash whilst writing a
> > subroutine.
> >
> > What happens is that if I pass a hash by reference to a subroutine,
> > traverse that hash using a while() loop, and return in the middle of
> > the loop, the hash is corrupted in some way.
>
> From the man pages:
>
> When the hash is entirely read, a null array is returned in list
> context (which when assigned produces a false ("0") value), and
> "undef" in scalar context. The next call to "each" after that will start
> iterating again. There is a single iterator for each hash, shared by
> all "each", "keys", and "values" function calls in the program; it can
> be reset by reading all the elements from the hash, or by
> evaluating "keys HASH" or "values HASH".
>
> This means that if you leave the while( ($k,$v) = each %hash)
> before it finishes iterating over the whole hash then the keys or
> each that follow will ONLY read the REST of the hash.
>
> So it would be best to eval
>
>       each %hash;
>
> in void context if you do so. :
>
>       while( my( $key, $value ) = each %{$hash} ) {
>               if( $value eq 'value1' ) {
>                       each %$hash;
>                       return;
>               }
>       }
>
> Jenda
>
> =========== [EMAIL PROTECTED] == http://Jenda.Krynicky.cz ==========
> There is a reason for living. There must be. I've seen it somewhere.
> It's just that in the mess on my table ... and in my brain.
> I can't find it.
>                                       --- me
>
>


_______________________________________________
ActivePerl mailing list
[EMAIL PROTECTED]
http://listserv.ActiveState.com/mailman/listinfo/activeperl

Reply via email to