Skip to content

Commit

Permalink
Guarantee that %hash->each iterates through the entire hash.
Browse files Browse the repository at this point in the history
Closes #7
  • Loading branch information
schwern committed Sep 27, 2011
1 parent 6c93b19 commit 8a0b95d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Changes
@@ -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.
Expand All @@ -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!
Expand Down
8 changes: 8 additions & 0 deletions lib/autobox/Core.pm
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions t/each.t
Expand Up @@ -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.