Skip to content

Instantly share code, notes, and snippets.

@xtetsuji
Created August 7, 2012 01:39
Show Gist options
  • Save xtetsuji/3280541 to your computer and use it in GitHub Desktop.
Save xtetsuji/3280541 to your computer and use it in GitHub Desktop.
perl map syntax implement by perl itself without using CORE::map.
#!/usr/bin/perl
# ogata 2012/08/07
# perl map syntax implement by perl itself without using CORE::map.
sub map2 (&@) {
my $code = shift;
my @args = @_;
require Scalar::Util;
my $type = Scalar::Util::reftype($code);
unless($type and $type eq 'CODE') {
require Carp;
Carp::croak("Not a subroutine reference");
}
my @ret;
for (@args) {
push @ret, &{$code};
}
return @ret;
}
### Test
use Test::More;
is "1,4,9,16,25,36,49,64,81,100", join( ",", map2 { $_ ** 2 } 1..10 ), "1 to 10 powered by 2 mappping.";
is "ABCDE", join("", map2 { uc $_ } "a".."e" ), "Uppercase ABCDE match.";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment