$line = "x" x 38 . "\n"; sub test { ($res) = ($_[0] =~ /((?:[^\n]{0,40}\n){0,4})/); if ($res) { print "yes\n"; } else { print "no\n"; } } test( "x$line" x 4 ); # 39 x 4 test( "xx$line" x 4 ); # 40 x 4 test( "xxx$line" x 4 ); # 41 x 4 test( "xx$line" x 3 ); # 40 x 3 test( "x$line" x 5 ); # 39 x 5