# create a "cache": "is this a NETID?" # (if I understand your variables correctly...) my %ids = map { $_ => 1 } values %totalnetname; my %ECLDATA = (); { # lexical scope for leftovers my @leftovers = (); while (my $entry = shift @ECL_STAT) { # ignore non-|-delimited lines next unless my ($netid) = split /\|/, $_; # push lines which begin with any NETID push ( $ids{$netid} ? @{ $ECLDATA{$netid} } : @leftovers ), $_; } @ECL_STAT = @leftovers; } for my $key (@totalkeys) { my $NETID = $totalnetname{$key}; my @ECLDATA = @{ $ECLDATA{$NETID} }; # ... lots, as before. }