הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Control Structures

Flow Control keywords help us control the flow of our programs. Perl is very similar to c in this aspect, with loops, branches and subroutines.

In perl, we can use these structures normally (like we would in a c program), but also as statement modifiers.
Let's examine some syntax and examples.

Perl Control Flow Structures

if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

while (EXPR) BLOCK
while (EXPR) BLOCK continue BLOCK

until (EXPR) BLOCK
until (EXPR) BLOCK continue BLOCK

for (EXPR; EXPR; EXPR) BLOCK
foreach VAR (LIST) BLOCK
foreach VAR (LIST) BLOCK continue BLOCK

Perl Loop Examples

use strict;
use warnings;

for (my $i=0; $i < 10; ++$i) {
  print "counting: $i\n";
}

my $i=0;
while ($i < 10) {
    print "Counting: $i\n";
    $i++;
}

foreach my $i (1..10) {
  print "Counting: $i\n";
}

There will be loops in which we're not interested in the loop counter, only the number of times a command is executed. For example, we may want to implement multiplication by adding a number to itself many times. For those cases, we can (and should) use anonymous for loop. That loop has no loop iteration variable, which means one less name to follow when reading the code. Can you guess which variable will take you to the loop iteration counter ?

use strict;
use warnings;

my $x   = 3;
my $mul = 0;
for (1..4) {
    $mul += $x;
}
print "3 * 4 = $mul\n";

Loop Controls

Loop controls provide a means of controlling the loop from inside an iteration. The following table summarizes them:

Perl Keyword C Keyword Meaning
next continue Jump to the next loop iteration
last break Jump to the first line following the loop (skipping all remaining iterations)
redo - Go back to the beginning of this iteration

Let's explore those keywords in some examples:

use Modern::Perl;
 
my $x = 10;
 
while($x > 0) {
        next if $x > 5;
        say $x;
} continue {
        $x--;
}
 
use Modern::Perl;
 
my $x = 10;
 
while($x > 0) {
        last if $x == 5;
        say $x;
} continue {
        $x--;
}
use Modern::Perl;
 
my $x = 10;
 
while($x > 0) {
        say $x;
        redo if $x == 5;
} continue {
        $x--;
}
course: