Created
March 6, 2012 02:01
-
-
Save syohex/1982855 to your computer and use it in GitHub Desktop.
Implementation of each_with_index in Perl
This file contains hidden or 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
#!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