... use strict; my $countSpaces = sub { my $spaces = tr/ //; return qr{(?!)} if $spaces > 1; return qr{(?=)}; }; while () { chomp; print "$_ [", /(.*)(??{$countSpaces->()})/ ? "OK]\n" : "BAD]\n"; } __DATA__ this line has more than one space that_is_5_spaces This isonespaceonly therearenospaceshere