Whatever color the input is it returns "green" :(
sub next_traffic_lights {
my ($x) = @_;
if ($x == "red") {
return "green";
}
elsif ($x == "green") {
return "yellow";
} else {
return "red";
}
}
Whatever color the input is it returns "green" :(
sub next_traffic_lights {
my ($x) = @_;
if ($x == "red") {
return "green";
}
elsif ($x == "green") {
return "yellow";
} else {
return "red";
}
}
In Perl ==
means numerical equivalence where eq
is string equivalence. You just need to flip those ==
to eq
to do the right comparisons.
Both "red"
and "green"
are equal to zero numerically, so they're considered identical here using numerical comparison.
When writing code like this you should steer towards a lookup table anyway, as this is basically a simple state machine:
my %next_light = (
"red" => "green",
"yellow" => "red",
"green" => "yellow"
);
sub next_traffic_lights {
return $next_light{$_[0]};
}