foreach my $n (@natures){ open (OUT, "> $n.txt") or die "blah blah $! \n" while(){ print OUT $_ if $_ =~ /$n/; } }