This repository has been archived by the owner on Jun 6, 2018. It is now read-only.
forked from evalEmpire/perl5i
-
Notifications
You must be signed in to change notification settings - Fork 1
/
each.t
120 lines (88 loc) · 2.33 KB
/
each.t
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/perl
use perl5i::latest;
use Test::More;
note "each with no signature"; {
my %want = (foo => 23, bar => 42);
my %have;
%want->each( sub { $have{$_[0]} = $_[1] } );
is_deeply \%have, \%want;
}
note "each with one arg"; {
my %want = (foo => 23, bar => 42);
my %have;
%want->each( func($k) { $have{$k} = 1 } );
is_deeply \%have, { foo => 1, bar => 1 };
}
note "each with two args"; {
my %want = (foo => 23, bar => 42);
my %have;
%want->each( func($k,$v) { $have{$k} = $v } );
is_deeply \%have, \%want;
}
note "each call is safe"; {
my %want = (foo => 23, bar => 42, baz => 99, biff => 66);
# Call each once on %want to start the iterator attached to %want
my($k,$v) = each %want;
my %have;
%want->each( func($k,$v) { $have{$k} = $v } );
is_deeply \%have, \%want;
}
note "Tests adapted from Hash::StoredIterator";
my @want_outer = (
[a => 1],
[b => 2],
[c => 3],
);
my @want_inner = (
[a => 1],
[a => 1],
[a => 1],
[b => 2],
[b => 2],
[b => 2],
[c => 3],
[c => 3],
[c => 3],
);
my %hash = ( a => 1, b => 2, c => 3 );
sub interference {
my @garbage = keys(%hash), values(%hash);
while ( my ( $k, $v ) = each(%hash) ) {
# Effectively do nothing
my $foo = $k . $v;
}
};
{
my @inner;
my @outer;
%hash->each( func( $k, $v ) {
ok( $k, "Got key" );
ok( $v, "Got val" );
is( $k, $_, '$_ is set to key' );
is( $k, $a, '$a is set to key' );
is( $v, $b, '$b is set to val' );
push @outer => [$k, $v];
interference();
%hash->each( func( $k2, $v2 ) {
is( $k2, $_, '$_ is set to key' );
is( $k2, $a, '$a is set to key' );
is( $v2, $b, '$b is set to val' );
push @inner => [$k, $v];
interference();
});
is( $k, $_, '$_ is not squashed by inner loop' );
is( $k, $a, '$a is not squashed by inner loop' );
is( $v, $b, '$a is not squashed by inner loop' );
});
is_deeply(
[sort { $a->[0] cmp $b->[0] } @outer],
\@want_outer,
"Outer loop got all keys"
);
is_deeply(
[sort { $a->[0] cmp $b->[0] } @inner],
\@want_inner,
"Inner loop got all keys multiple times"
);
}
done_testing;