Permalink
Browse files

Guarantee that %hash->each iterates through the entire hash.

Closes #7
  • Loading branch information...
1 parent 6c93b19 commit 8a0b95dca519ef2c696a14fff8ec34f32167c464 @schwern schwern committed Sep 27, 2011
Showing with 28 additions and 0 deletions.
  1. +7 −0 Changes
  2. +8 −0 lib/autobox/Core.pm
  3. +13 −0 t/each.t
View
@@ -1,5 +1,11 @@
Revision history for autobox::Core
+1.22
+ New Features
+ - %hash->each is now guaranteed to iterate through the complete hash,
+ unlike each(%hash). [github 7]
+
+
1.21 Mon Sep 26 16:15:19 PDT 2011
New Features
- $string->reverse will now always reverse the string regardless of context.
@@ -15,6 +21,7 @@ Revision history for autobox::Core
- removed unnecessary prototypes on methods (schwern)
- updated dependency on autobox
+
1.2 Fri Mar 19 12:11:00 2010
- fixes version 1.1 losing the MANIFEST and being essentially
a null upload. Bah!
View
@@ -380,6 +380,8 @@ the code reference is invoked with the key and the corresponding value as argume
my $hashref = { foo => 10, bar => 20, baz => 30, quux => 40 };
$hashref->each(sub { print $_[0], ' is ', $_[1], "\n" });
+Unlike regular C<each>, this each will always iterate through the entire hash.
+
There is currently no way to have the elements sorted before they are handed to the
code block. If someone requests a way of passing in a sort criteria, I'll implement it.
@@ -1046,9 +1048,15 @@ sub flatten { %{$_[0]} }
sub each {
my $hash = CORE::shift;
my $cb = CORE::shift;
+
+ # Reset the each iterator. (This is efficient in void context)
+ CORE::keys %$hash;
+
while((my $k, my $v) = CORE::each(%$hash)) {
$cb->($k, $v);
}
+
+ return;
}
# Keywords related to classes and object-orientedness
View
@@ -17,3 +17,16 @@ my @added;
@array->each( sub { push @added, $_[0] + 1 } );
is_deeply [ sort @added ], [ qw(2 3 4) ];
+
+# Ensure each() always iterates through the whole hash
+{
+ my %want = (foo => 23, bar => 42, baz => 99, biff => 66);
+
+ # Call each once on %want to start the iterator attached to %want
+ my($k,$v) = each %want;
+
+ my %have;
+ %want->each( sub { $have{$_[0]} = $_[1] } );
+
+ is_deeply \%have, \%want;
+}

0 comments on commit 8a0b95d

Please sign in to comment.