Skip to content

Instantly share code, notes, and snippets.

@syohex
Created March 6, 2012 02:01
Show Gist options
  • Save syohex/1982855 to your computer and use it in GitHub Desktop.
Save syohex/1982855 to your computer and use it in GitHub Desktop.
Implementation of each_with_index in Perl
#!perl
use strict;
use warnings;
sub each_with_index (\@) {
my $array_ref = shift;
my $length = scalar @{$array_ref};
my $index = 0;
return sub {
return if $index >= $length;
my $elem = $array_ref->[$index];
return wantarray ? ($elem, $index++) : $elem;
};
}
my @alphabets = 'a'..'z';
my $iter = each_with_index(@alphabets);
while (my ($char, $index) = $iter->()) {
printf "'%s' is %2d\n", $char, $index;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment