my @possible_next_steps = @{$links{$start}}; my @unvisited_nodes = grep { ! $visited->{$_} } @possible_next_steps; # Now, for each unvisited node, see if we can reach the goal from there for (@unvisited_nodes) { ... };