for( my $i = 0; $i <= $#lines; $i++ ) { if ( $lines[$i] =~ s/^SY(?= )/CN/ ) { if ( defined $lines[$i+1] ) { $lines[$i+1] =~ s/^SY(?= )/ /; } } } #### my $previous_line_matched = 0; foreach my $line ( @lines ) { if ( $previous_line_matched ) { $line =~ s/^SY(?= )/ /; } if ( $line =~ s/^SY(?= )/CN/ ) { $previous_line_matched = 1; next; } $previous_line_matched = 0; }