Firstly I'd avoid using $a and $b (in case they interfere with sort functions you may write later). Next, it is probably best to first write what you mean and then decide whether it needs factorising into a grep. But we can't know that without knowing what your pairwise structure looks like.