-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloops.pl
73 lines (54 loc) · 1.2 KB
/
loops.pl
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
use strict;
use warnings;
my @array = ("azul", "rojo","negro");
my $i = 0;
#while
while($i < @array) {
print $i, ": ", $array[$i];
$i++;
};
#until
$i = 0;
until($i >= scalar @array) {
print $i, ": ", $array[$i];
$i++;
}
#do
$i = 0;
do {
print $i, ": ", $array[$i];
$i++;
} while ($i < scalar @array);
$i = 0;
do {
print $i, ": ", $array[$i];
$i++;
} until ($i >= scalar @array);
#foreach
foreach my $string ( @array ) {
print $string;
};
foreach my $i ( 0 .. $#array ) {
print $i, ": ", $array[$i];
};
my %scientists = (
"Newton" => "Isaac",
"Einstein" => "Albert",
"Darwin" => "Charles",
);
foreach my $key (keys %scientists) {
print $key, ": ", $scientists{$key}."\n";
};
#If you don't provide an explicit iterator, Perl uses a default iterator, $_. $_ is the first and friendliest of the built-in variables:
foreach ( @array ) {
print $_;
};
#If using the default iterator, and you only wish to put a single statement inside your loop, you can use the super-short loop syntax:
print $_ foreach @array;
#Loop Control
CANDIDATE: for my $candidate ( 2 .. 100 ) {
for my $divisor ( 2 .. sqrt $candidate ) {
next CANDIDATE if $candidate % $divisor == 0;
}
print $candidate." is prime\n";
}