use 5.010; ... my $pre_b = qr{ ... }xms; my $pre_weis = qr{ ... }xms; my $b_was_seen; while (my $line = <$input_filehandle>) { # check for trigger condition/substitution pattern sequence. # ASSUME: 'b' and 'Weis' cannot both occur in same line. if ($line =~ m{ \A $pre_b b }xms) { # flag 'b' was seen in this line. $b_was_seen = 1; } elsif ($b_was_seen) { # attempt substitution if 'b' seen in previous line. $line =~ s{ \A $pre_weis \K Weis }{Schwarz}xms; $b_was_seen = 0; } # write each (possibly altered) line to output file. print $output_filehandle $line; }