[% setvar title Fix iteration of nested hashes %]

This file is part of the Perl 6 Archive

Note: these documents may be out of date. Do not use as reference!

To see what is currently happening visit http://www.perl6.org/


Fix iteration of nested hashes


  Maintainer: Damian Conway <damian@conway.org>
  Date: 18 Sep 2000
  Last Modified: 25 Sep 2000
  Mailing List: perl6-language@perl.org
  Number: 255
  Version: 3
  Status: Retracted


The thread:


points out some serious problems that the proposal did not address. As I do not have time to find/invent good solutions, I am forced to withdraw the proposal.

Anyone wishing to take up the cudgels against this annoying problem has my encouragement to pick whatever they like from the bones of this document.


This RFC proposes that the internal cursor iterated by the each function be stored in the pad of the block containing the each, rather than being stored within the hash being iterated.


Currently, nesting two each iterations on the same hash leads to unexpected behaviour, because both eachs advance the same internal cursor within the hash. For example:

        %desc = ( blue  => "moon",
                  green => "egg",
                  red   => "Baron" );

        while ( my ($key1,$value1) = each %desc )
                while ( my ($key2,$value2) = each %desc )
                        print "$value2 is not $key1\n"
                                unless $key1 eq $key2;
        print "(finished)\n";

It is proposed that each each maintain its own cursor (stored in the pad of the block containing it) so that the above example DWIMs.


Minimal. No-one nests iterators now because it doesn't work.

Usages such as:

	$x = each %hash;
	$y = each %hash;
	@z = each %hash;

would change their behaviour, but could be translated if p52p6 defined:

	sub p5_each(\%) { each %{$_[0]} }

and globally replaced each Perl 5 each by p5_each.

There would not (necessarily) be any effect on the use of FIRSTKEY and NEXTKEY in tied hashes, since the compiler could still determine which should be called. However, tied hashes that use an internal cursor might behave differently, if nested.


Store the cursor in the pad of the block in which the each is defined, rather than within hash.


RFC 136: (Implementation of hash iterators) suggests separate iterators for each and keys/values.