Update to Scalar-List-Utils-1.15
[p5sagit/p5-mst-13.2.git] / ext / List / Util / t / reduce.t
CommitLineData
1bfb5477 1#!./perl
2
f4a2945e 3BEGIN {
1bfb5477 4 unless (-d 'blib') {
f4a2945e 5 chdir 't' if -d 't';
6 @INC = '../lib';
6b05f64e 7 require Config; import Config;
1bfb5477 8 keys %Config; # Silence warning
6b05f64e 9 if ($Config{extensions} !~ /\bList\/Util\b/) {
10 print "1..0 # Skip: List::Util was not built\n";
11 exit 0;
12 }
1bfb5477 13 }
f4a2945e 14}
15
1bfb5477 16
f4a2945e 17use List::Util qw(reduce min);
cf083cf9 18use Test::More tests => 14;
f4a2945e 19
cf083cf9 20my $v = reduce {};
f4a2945e 21
cf083cf9 22is( $v, undef, 'no args');
f4a2945e 23
cf083cf9 24$v = reduce { $a / $b } 756,3,7,4;
25is( $v, 9, '4-arg divide');
f4a2945e 26
cf083cf9 27$v = reduce { $a / $b } 6;
28is( $v, 6, 'one arg');
f4a2945e 29
30@a = map { rand } 0 .. 20;
cf083cf9 31$v = reduce { $a < $b ? $a : $b } @a;
32is( $v, min(@a), 'min');
f4a2945e 33
34@a = map { pack("C", int(rand(256))) } 0 .. 20;
cf083cf9 35$v = reduce { $a . $b } @a;
36is( $v, join("",@a), 'concat');
1bfb5477 37
38sub add {
39 my($aa, $bb) = @_;
40 return $aa + $bb;
41}
42
cf083cf9 43$v = reduce { my $t="$a $b\n"; 0+add($a, $b) } 3, 2, 1;
44is( $v, 6, 'call sub');
1bfb5477 45
46# Check that eval{} inside the block works correctly
cf083cf9 47$v = reduce { eval { die }; $a + $b } 0,1,2,3,4;
48is( $v, 10, 'use eval{}');
1bfb5477 49
cf083cf9 50$v = !defined eval { reduce { die if $b > 2; $a + $b } 0,1,2,3,4 };
51ok($v, 'die');
60f3865b 52
cf083cf9 53sub foobar { reduce { (defined(wantarray) && !wantarray) ? $a+1 : 0 } 0,1,2,3 }
54($v) = foobar();
55is( $v, 3, 'scalar context');
60f3865b 56
09c2a9b8 57sub add2 { $a + $b }
58
cf083cf9 59$v = reduce \&add2, 1,2,3;
60is( $v, 6, 'sub reference');
09c2a9b8 61
cf083cf9 62$v = reduce { add2() } 3,4,5;
63is( $v, 12, 'call sub');
09c2a9b8 64
09c2a9b8 65
cf083cf9 66$v = reduce { eval "$a + $b" } 1,2,3;
67is( $v, 6, 'eval string');
09c2a9b8 68
cf083cf9 69$a = 8; $b = 9;
70$v = reduce { $a * $b } 1,2,3;
71is( $a, 8, 'restore $a');
72is( $b, 9, 'restore $b');