my @ar = (); # empty array while(<>){ #for every match in the line #(if there are more than one email in a line) while(/([^<]*)<\/a>/g){ push @ar, "$3\t$2"; } } open ... for(sort @ar){ my ($name, $email) = split/\t/; print OUT qq($name
\n); }