Created
August 27, 2019 10:01
-
-
Save bdw/2c89f23227fca648dfb1d7a1348e43ad to your computer and use it in GitHub Desktop.
Reimplementation of List::Util for running on perl 5.10
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
#!/usr/bin/env perl | |
package ListUtil; | |
# Reimplementation of List::Util for running on perl 5.10 | |
use strict; | |
use warnings; | |
use Exporter 'import'; | |
@ListUtil::EXPORT_OK = qw(pairgrep pairmap pairkeys pairvalues); | |
sub pairgrep(&@) { | |
my $code = shift; | |
my @result; | |
while (@_) { | |
local ($a, $b) = splice @_, 0, 2; | |
push @result, $a, $b if $code->(); | |
} | |
return @result; | |
} | |
sub pairmap(&@) { | |
my $code = shift; | |
my @result; | |
while (@_) { | |
local ($a, $b) = splice @_, 0, 2; | |
push @result, $code->(); | |
} | |
return @result; | |
} | |
sub pairkeys { | |
pairmap { $a } @_; | |
} | |
sub pairvalues { | |
pairmap { $b } @_; | |
} | |
sub test { | |
require Test; Test->import; | |
plan(tests => 4); | |
local $" = ','; | |
my @a; | |
@a = pairkeys(1..10); | |
ok("@a" eq "1,3,5,7,9"); | |
@a = pairvalues(1..10); | |
ok("@a" eq "2,4,6,8,10"); | |
@a = pairgrep { $a > 5 && $b < 10 } 1..10; | |
ok("@a" eq "7,8"); | |
@a = pairmap { $a * $b } 1..10; | |
ok("@a" eq "2,12,30,56,90"); | |
} | |
test() unless caller(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment