summaryrefslogtreecommitdiff
path: root/gnu/usr.bin/perl/t/cmd/for.t
blob: 27fb5a25178a179dac4f548068b6a33ccbc84d2a (plain)
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
#!./perl

print "1..14\n";

for ($i = 0; $i <= 10; $i++) {
    $x[$i] = $i;
}
$y = $x[10];
print "#1	:$y: eq :10:\n";
$y = join(' ', @x);
print "#1	:$y: eq :0 1 2 3 4 5 6 7 8 9 10:\n";
if (join(' ', @x) eq '0 1 2 3 4 5 6 7 8 9 10') {
	print "ok 1\n";
} else {
	print "not ok 1\n";
}

$i = $c = 0;
for (;;) {
	$c++;
	last if $i++ > 10;
}
if ($c == 12) {print "ok 2\n";} else {print "not ok 2\n";}

$foo = 3210;
@ary = (1,2,3,4,5);
foreach $foo (@ary) {
	$foo *= 2;
}
if (join('',@ary) eq '246810') {print "ok 3\n";} else {print "not ok 3\n";}

for (@ary) {
    s/(.*)/ok $1\n/;
}

print $ary[1];

# test for internal scratch array generation
# this also tests that $foo was restored to 3210 after test 3
for (split(' ','a b c d e')) {
	$foo .= $_;
}
if ($foo eq '3210abcde') {print "ok 5\n";} else {print "not ok 5 $foo\n";}

foreach $foo (("ok 6\n","ok 7\n")) {
	print $foo;
}

sub foo {
    for $i (1..5) {
	return $i if $_[0] == $i;
    }
}

print foo(1) == 1 ? "ok" : "not ok", " 8\n";
print foo(2) == 2 ? "ok" : "not ok", " 9\n";
print foo(5) == 5 ? "ok" : "not ok", " 10\n";

sub bar {
    return (1, 2, 4);
}

$a = 0;
foreach $b (bar()) {
    $a += $b;
}
print $a == 7 ? "ok" : "not ok", " 11\n";

$loop_count = 0;
for ("-3" .. "0") {
    $loop_count++;
}
print $loop_count == 4 ? "ok" : "not ok", " 12\n";

# modifying arrays in loops is a no-no
@a = (3,4);
eval { @a = () for (1,2,@a) };
print $@ =~ /Use of freed value in iteration/ ? "ok" : "not ok", " 13\n";

# [perl #30061] double destory when same iterator variable (eg $_) used in
# DESTROY as used in for loop that triggered the destroy

{

    my $x = 0;
    sub X::DESTROY {
	my $o = shift;
	$x++;
	1 for (1);
    }

    my %h;
    $h{foo} = bless [], 'X';
    delete $h{foo} for $h{foo}, 1;
    print $x == 1 ? "ok" : "not ok", " 14 - double destroy, x=$x\n";
}