Liam Liam - 6 months ago 20
Perl Question

Multiple else if conditions true

I have multiple

elsif
conditions in a else if statement.

What is the flow of the statement if multiple conditions are true? So in the simplistic example below which serves as a demonstration only, is the the second elsif condition ever reached?

my $i = 1;

if ($i == 1){
}
elsif (i == 2){
}
elsif (i == 1){
}
else{
}

Answer

Easy to try:

use feature ":5.10";

my $i = 1;

if ($i == 1) {
    say "A"; # this is the only branch executed
} elsif (i == 2) {
    say "B";
} elsif (i == 1) {
    say "C";
} else {
    say "D";
}

Each elsif is only considered if the previous conditions did not succeed. You can see that the comparisons are not even tried:

if ($i == 1) {
    say "A";
} elsif (i == 2/0) { # This doesn’t blow up since the comparison is never tried
    say "B";
} else {
    say "C";
}
Comments