Flow control

    The last one is false because "0" becomes 0 in numeric context, which is false by the third rule.

    postfix controls

    A simple or unless block might look like this:

    1. if ($is_frobnitz) {
    2. print "FROBNITZ DETECTED!\n";
    3. }

    In these cases, simple statements can have the if or unless appended to the end.

    1. print "FROBNITZ DETECTED!\n" if $is_frobnitz;
    2. die "BAILING ON FROBNITZ!\n" unless $deal_with_frobnitz;

    This also works for while and .

    1. print $i++ . "\n" while $i < 10;

    You may see foreach used in place of for. The two are interchangable. Most people use foreach for the last two styles of loops above.

    do blocks

    do allows Perl to use a block where a statement is expected.

    1. open( my $file, '<', $filename ) or die "Can't open $filename: $!"

    But if you need to do something else:

    1. open( my $file, '<', $filename ) or do {
    2. die "Aborting: Can't open $filename: $!\n";
    3. };

    The following are also equivalent:

    1. if ($condition) { action(); }
    2. do { action(); } if $condition;

    If you're coming from another language, you might be used to case statements. Perl doesn't have them.

    The closest we have is elsif:

    1. if ($condition_one) {
    2. action_one();
    3. }
    4. elsif ($condition_two) {
    5. action_two();
    6. }
    7. ...
    8. else {
    9. action_n();
    10. }

    There is no way to fall through cases cleanly.

    next/last/continue/redo

    Consider the following loop:

    1. $i = 0;
    2. last if $i > 3;
    3. $i++;
    4. next if $i == 1;
    5. redo if $i == 2;
    6. }
    7. continue {
    8. print "$i\n";
    9. }
    1. 1
    2. 3
    3. 4
    • next skips to the end of the block and continues or restarts
    • redo jumps back to the beginning of the loop immediately
    • skips to the end of the block and stops the loop from executing again
    • continue is run at the end of the block

    Submit a PR to