This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Revert core fixes for IO-Compress following IO-Compress update
[perl5.git] / cpan / List-Util / lib / List / Util / PP.pm
CommitLineData
2ff28616
GB
1# List::Util::PP.pm
2#
3# Copyright (c) 1997-2009 Graham Barr <gbarr@pobox.com>. All rights reserved.
4# This program is free software; you can redistribute it and/or
5# modify it under the same terms as Perl itself.
6
7package List::Util::PP;
8
9use strict;
10use warnings;
11use vars qw(@ISA @EXPORT $VERSION $a $b);
12require Exporter;
13
14@ISA = qw(Exporter);
15@EXPORT = qw(first min max minstr maxstr reduce sum shuffle);
16$VERSION = "1.21";
17$VERSION = eval $VERSION;
18
19sub reduce (&@) {
20 my $code = shift;
21 unless(ref($code)) {
22 require Carp;
23 Carp::croak("Not a subroutine reference");
24 }
25 no strict 'refs';
26
27 return shift unless @_ > 1;
28
29 use vars qw($a $b);
30
31 my $caller = caller;
32 local(*{$caller."::a"}) = \my $a;
33 local(*{$caller."::b"}) = \my $b;
34
35 $a = shift;
36 foreach (@_) {
37 $b = $_;
38 $a = &{$code}();
39 }
40
41 $a;
42}
43
44sub first (&@) {
45 my $code = shift;
46
47 foreach (@_) {
48 return $_ if &{$code}();
49 }
50
51 undef;
52}
53
54
55sub sum (@) { reduce { $a + $b } @_ }
56
57sub min (@) { reduce { $a < $b ? $a : $b } @_ }
58
59sub max (@) { reduce { $a > $b ? $a : $b } @_ }
60
61sub minstr (@) { reduce { $a lt $b ? $a : $b } @_ }
62
63sub maxstr (@) { reduce { $a gt $b ? $a : $b } @_ }
64
65sub shuffle (@) {
66 my @a=\(@_);
67 my $n;
68 my $i=@_;
69 map {
70 $n = rand($i--);
71 (${$a[$n]}, $a[$n] = $a[$i])[0];
72 } @_;
73}
74
751;