Skip to content

Instantly share code, notes, and snippets.

@bdw
Created Aug 27, 2019
Embed
What would you like to do?
Reimplementation of List::Util for running on perl 5.10
#!/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