The problem is that you're trying to do a pattern match against an undefined variable (if the regex doesn't match, or doesn't match enough, $3 will be undefined). My solution drops out of the "loop" immediately in this case, so it never tries to do the pattern match. Roy Johnson's solution avoids entering the loop at all if $3 is undefined.