my $rx_altloc = qr/ ^(ATOM.{9} # match only atom records (.{3}) # capture atom name (and any space included) (.) # capture alternate location identifier \w{3} # match the amino acid name (.{6}) # capture chain and residue number .+$ [\r\n]) # match the rest of the line (?:(^ATOM.{9} # make sure the next line(s) is an atom record (?=\2).{3} # make sure same atom name (?!\3). # make sure different alternate location \w{3} # don't care if it's the same residue type (?=\4).{6} # make sure it's the same chain and residue .+$ [\r\n])+) # match the rest of the line (?{ $altloc = $3; }) /xm; ... $file_contents =~ s/$rx_altloc/$1/g; /xm;