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:
- if ($is_frobnitz) {
- print "FROBNITZ DETECTED!\n";
- }
In these cases, simple statements can have the if
or unless
appended to the end.
- print "FROBNITZ DETECTED!\n" if $is_frobnitz;
- die "BAILING ON FROBNITZ!\n" unless $deal_with_frobnitz;
This also works for while
and .
- 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.
- open( my $file, '<', $filename ) or die "Can't open $filename: $!"
But if you need to do something else:
- open( my $file, '<', $filename ) or do {
- die "Aborting: Can't open $filename: $!\n";
- };
The following are also equivalent:
- if ($condition) { action(); }
- 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
:
- if ($condition_one) {
- action_one();
- }
- elsif ($condition_two) {
- action_two();
- }
- ...
- else {
- action_n();
- }
There is no way to fall through cases cleanly.
next/last/continue/redo
Consider the following loop:
- $i = 0;
- last if $i > 3;
- $i++;
- next if $i == 1;
- redo if $i == 2;
- }
- continue {
- print "$i\n";
- }
- 1
- 3
- 4
next
skips to the end of the block and continues or restartsredo
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