Created
December 6, 2017 23:46
-
-
Save Grinnz/a7c689ab353c2104de3cb71b6cbc8e57 to your computer and use it in GitHub Desktop.
Syntax::Keyword::WhileEach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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