# if @tag contains simple words my $re = join '|', @tag; # if they can be more complicated: # my $re = join '|', map { "(?:$_)" } @tag; open my $out, '+>', "Result_file.txt" or die "Can't open file Result_file.txt for writing: $!"; open my $in, '<', 'Input_file.dat' or die "Can't read Input_file.dat: $!"; while(<$in>){ print $out $_ if m/$re/o; } close $in; close $out;