use strict; use warnings; open(OUT, '>', "out.txt"); open(FH, "test.res") or die "$!"; while(){ chomp; if($_ =~ m/--gnu.+-D/){ my @words = split(/\s+/, $_); foreach my $word(@words){ if($word =~ m/^-D/){ print OUT "$word\t"; } } last; } } close(FH); close(OUT);