my %visited = map { $_ => undef } (1 .. 4); my @unvisited = (1 .. 9); while ( @unvisited ) { my $router = shift @unvisited; next if exists $visited{$router}; visit ( $router, \@unvisited ); # Adds routers to @unvisited $visited{$router} = undef; }