xref: /openbsd-src/gnu/usr.bin/perl/t/cmd/for.t (revision 3d61058aa5c692477b6d18acfbbdb653a9930ff9)
1#!./perl
2
3print "1..16\n";
4
5for ($i = 0; $i <= 10; $i++) {
6    $x[$i] = $i;
7}
8$y = $x[10];
9print "#1	:$y: eq :10:\n";
10$y = join(' ', @x);
11print "#1	:$y: eq :0 1 2 3 4 5 6 7 8 9 10:\n";
12if (join(' ', @x) eq '0 1 2 3 4 5 6 7 8 9 10') {
13	print "ok 1\n";
14} else {
15	print "not ok 1\n";
16}
17
18$i = $c = 0;
19for (;;) {
20	$c++;
21	last if $i++ > 10;
22}
23if ($c == 12) {print "ok 2\n";} else {print "not ok 2\n";}
24
25$foo = 3210;
26@ary = (1,2,3,4,5);
27foreach $foo (@ary) {
28	$foo *= 2;
29}
30if (join('',@ary) eq '246810') {print "ok 3\n";} else {print "not ok 3\n";}
31
32for (@ary) {
33    s/(.*)/ok $1\n/;
34}
35
36print $ary[1];
37
38# test for internal scratch array generation
39# this also tests that $foo was restored to 3210 after test 3
40for (split(' ','a b c d e')) {
41	$foo .= $_;
42}
43if ($foo eq '3210abcde') {print "ok 5\n";} else {print "not ok 5 $foo\n";}
44
45foreach $foo (("ok 6\n","ok 7\n")) {
46	print $foo;
47}
48
49sub foo {
50    for $i (1..5) {
51	return $i if $_[0] == $i;
52    }
53}
54
55print foo(1) == 1 ? "ok" : "not ok", " 8\n";
56print foo(2) == 2 ? "ok" : "not ok", " 9\n";
57print foo(5) == 5 ? "ok" : "not ok", " 10\n";
58
59sub bar {
60    return (1, 2, 4);
61}
62
63$a = 0;
64foreach $b (bar()) {
65    $a += $b;
66}
67print $a == 7 ? "ok" : "not ok", " 11\n";
68
69$loop_count = 0;
70for ("-3" .. "0") {
71    $loop_count++;
72}
73print $loop_count == 4 ? "ok" : "not ok", " 12\n";
74
75# modifying arrays in loops is a no-no
76#  - unless the stack is reference-counted
77@a = (3,4);
78eval { @a = () for (1,2,@a) };
79print $@ =~   ((Internals::stack_refcounted() & 1)
80                  ?  qr/^$/
81                  : qr/Use of freed value in iteration/
82              )
83            ? "ok" : "not ok",
84            " 13 - freed value in iteration\n";
85
86# [perl #30061] double destory when same iterator variable (eg $_) used in
87# DESTROY as used in for loop that triggered the destroy
88
89{
90
91    my $x = 0;
92    sub X::DESTROY {
93	my $o = shift;
94	$x++;
95	1 for (1);
96    }
97
98    my %h;
99    $h{foo} = bless [], 'X';
100    delete $h{foo} for $h{foo}, 1;
101    print $x == 1 ? "ok" : "not ok", " 14 - double destroy, x=$x\n";
102}
103
104# [perl #78194] foreach() aliasing op return values
105for ("${\''}") {
106    print "not " unless \$_ == \$_;
107    print 'ok 15 - [perl \#78194] \$_ == \$_ inside for("$x"){...}',
108          "\n";
109}
110
111# [perl #123286] Lone C-style for in a block messes up the stack
112@_ = (1..3, do {for(0;0;){}}, 4..6);
113print "not " unless "@_" eq '1 2 3 0 4 5 6';
114print "ok 16 - [perl #78194] Lone C-style for in a block\n";
115