Skip to content

Instantly share code, notes, and snippets.

@Grinnz Grinnz/Iterator.pm
Created Dec 6, 2017

Embed
What would you like to do?
Syntax::Keyword::WhileEach
package Syntax::Keyword::WhileEach::Iterator;
use strict;
use warnings;
use Carp 'croak';
use Scalar::Util 'reftype';
sub new {
my ($class, $structure) = @_;
my $reftype = reftype $structure;
croak 'each requires a hash or array' unless $reftype eq 'HASH' or $reftype eq 'ARRAY';
my $is_hash = $reftype eq 'HASH';
my $keys = [$is_hash ? keys %$structure : 0..$#$structure];
return bless {is_hash => $is_hash, keys => $keys, structure => $structure}, $class;
}
sub next {
my ($self) = @_;
return () unless @{$self->{keys}};
my $key = shift @{$self->{keys}};
return wantarray
? ($key, $self->{is_hash} ? $self->{structure}{$key} : $self->{structure}[$key])
: $key;
}
1;
package Syntax::Keyword::WhileEach;
# some keyword magic that defines a keyword while_each that rewrites:
# LABEL: while_each (my ($k, $v) = each %foo) { ... }
# to:
# {
# my $iter = Syntax::Keyword::WhileEach::Iterator->new(\%foo);
# LABEL: while (my ($k, $v) = $iter->next) { ... }
# }
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.