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.
Beware: People are all too apt to ask for a solution to the wrong problem, hence we have no way of knowing given the lack of code so far whether this module is even a reasonable choice.