Flow control

Four values of false

There are four ways to have a false value in Perl:

  1. my $false = undef;
  2. $false = "";
  3. $false = 0;
  4. $false = "0";

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

postfix controls

A simple if 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 for.

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

for loops

There are three styles of for loops.

  1. my @array;
  2.  
  3. # Old style C for loops
  4. for (my $i = 0; $i < 10; $i++) {
  5. $array[$i] = $i;
  6. }
  7.  
  8. # Iterating loops
  9. for my $i (@array) {
  10. print "$i\n";
  11. }
  12.  
  13. # Postfix for loops
  14. print "$_\n" for @array;

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. close_open_data_source();
  3. die "Aborting: Can't open $filename: $!\n";
  4. };

The following are also equivalent:

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

As a special case, while runs the block at least once.

  1. do { action(); } while action_needed;

Perl has no switch or case

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. while ( 1 ) {
  3. last if $i > 3;
  4. $i++;
  5. next if $i == 1;
  6. redo if $i == 2;
  7. }
  8. continue {
  9. print "$i\n";
  10. }

prints

  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
  • last skips to the end of the block and stops the loop from executing again
  • continue is run at the end of the block

Want to contribute?

Submit a PR to github.com/petdance/perl101