Here's a solution that short circuits as soon as the comparison is larger than n: perl -ape '$_="match\n";$i=1;while($i<@F){((abs($F[$i]-$F[$i-1])||@F)>=@F)&&($_="not a $_")&&($i=@F);$i++}' Not as elegant as the others perhaps ...