0

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";
  }
 }
amon
  • 57,091
  • 2
  • 89
  • 149

1 Answers1

2

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]};
}
tadman
  • 208,517
  • 23
  • 234
  • 262