I am just looking for some advice on best practice. What is the best way to check for strings that are empty or include nothing but space character in them?
I generally use regex like this $string =~/^\s*$/ to see if the variable is blank. Is there a more accepted way or this is as good as any other? Is it better to use regex or to chomp and then check for empty string?
Thanks.
Personally, I generally invert the sense, and search for a single non-whitespace character. So I’d say something like:
As ikegami mentioned,
\s(and\S) can be a bit idiosyncratic about exactly what characters are considered whitespace, and you can use\p{Whitespace}(or in my case\P{Whitespace}) for more consistent results.Out of curiosity, I benchmarked
not /\S/versus/^\s*\z/. On an 80 character string (with Perl 5.14.2), I foundnot /\S/was about 20% faster for strings of spaces, and/^\s*\z/was about 30% faster for strings of non-spaces. It’s unlikely that checking for blank lines is the bottleneck in your program, but it certainly doesn’t hurt to use a simpler regexp.Example results for spaces:
Example results for non-spaces: