#!/usr/bin/perl #^^^ added / after ! use warnings; open my $wave, '>', 'Wave' or die "Can't open $wave: $!"; open my $keywords, '<', 'Agents' or die "Can't open keywords: $!"; open my $search_file, '<', 'Definitions' or die "Can't open search f +ile: $!"; my $keyword_or = join '|', map {chomp;qr/\Q$_\E/} <$keywords>; close $keywords; my $regex = qr|\b($keyword_or)\b|; OUTER: while (my $line = <$search_file>) { # ^^^^^^^ using just $_ is for chodes INNER: while ($line =~ m/$regex/g) #<~ why is this a "while" an not an "if"? { # skip if... if ( $line =~ m/(?:SCRIPTNAME|DESCRIPTION)/ ) { #^ if you're not capturing $1, don't keep it in memory next INNER; # ^^^^^ labels when using "nested" loops can be very helpful } print $wave $line; } } close $wave; close $search_file; Final note, you're opening yourself up to some adversarial input attacks by trusting $keyword_or