Commit | Line | Data |
---|---|---|
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 | ||
7 | package List::Util::PP; | |
8 | ||
9 | use strict; | |
10 | use warnings; | |
11 | use vars qw(@ISA @EXPORT $VERSION $a $b); | |
12 | require 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 | ||
19 | sub 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 | ||
44 | sub first (&@) { | |
45 | my $code = shift; | |
46 | ||
47 | foreach (@_) { | |
48 | return $_ if &{$code}(); | |
49 | } | |
50 | ||
51 | undef; | |
52 | } | |
53 | ||
54 | ||
55 | sub sum (@) { reduce { $a + $b } @_ } | |
56 | ||
57 | sub min (@) { reduce { $a < $b ? $a : $b } @_ } | |
58 | ||
59 | sub max (@) { reduce { $a > $b ? $a : $b } @_ } | |
60 | ||
61 | sub minstr (@) { reduce { $a lt $b ? $a : $b } @_ } | |
62 | ||
63 | sub maxstr (@) { reduce { $a gt $b ? $a : $b } @_ } | |
64 | ||
65 | sub 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 | ||
75 | 1; |