... another secret operator (the wrapping parentheses) ...
You have stumbled upon the secret operator known as operator precedence. In this case, there's no need for the disambiguation of grouping parentheses because the =~ binding operator is of higher precedence than <= or any other comparator.
c:\@Work\Perl\monks>perl -wMstrict -le
"sub not_too_many_dots { return $_[0] =~ tr/.// <= 1; }
;;
for my $s ('', qw(. .. ... ....)) {
printf qq{'$s' %stoo many dots \n},
not_too_many_dots($s) ? 'NOT ' : ''
;
}
"
'' NOT too many dots
'.' NOT too many dots
'..' too many dots
'...' too many dots
'....' too many dots
See
perlop (update: in particular Operator Precedence and Associativity). Of course, parenthetic grouping disambiguation never hurts, and many recommend it as a general BP to support readability/maintainability.
Update 1: I suspect the speedup you're seeing is due to operating directly upon an element of the aliased @_ subroutine argument array rather than burning the computrons needed to create lexical variables. See perlsub. (This would be in addition to using tr/// rather than m// for counting individual characters.)
Update 2: If you want to know what Perl thinks about the precedence and associativity of the operators you're using, use the O and B::Deparse modules. The -p flag produces full, explcit parenthetic grouping. (The useless assignments just produce some more grouping examples.)
c:\@Work\Perl\monks>perl -wMstrict -MO=Deparse,-p -le
"sub not_too_many_dots { return $_[0] =~ tr/.// <= 1; }
;;
for my $s ('', qw(. .. ... ....)) {
my $g = my $f = not_too_many_dots($s);
printf qq{'$s' %stoo many dots \n}, $f ? 'NOT ' : '';
print $g;
}
"
BEGIN { $^W = 1; }
BEGIN { $/ = "\n"; $\ = "\n"; }
sub not_too_many_dots {
use strict 'refs';
return((($_[0] =~ tr/.//) <= 1));
}
use strict 'refs';
foreach my($s) (('', ('.', '..', '...', '....'))) {
(my $g = (my $f = not_too_many_dots($s)));
printf("'${s}' %stoo many dots \n", ($f ? 'NOT ' : ''));
print($g);
}
-e syntax OK
Give a man a fish: <%-{-{-{-<
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.