|Perl Idioms Explained - my $count = () = /.../g
my $str = "here are some words";
my $count = () = $str =~ /\S+/g;
The "empty parentheses" idiom is one that is used to force list context on an expression, and yet return a scalar: the count of items in that list. We are often told that there is no way to get the size of a list -- it must either be iterated over, or stored in an array, or some other means -- because when you try
treating a list as a scalar, you're no longer dealing with a list: you're enforcing scalar context on some expression. Here are some examples:
my $last_operand = ("a", "b", "c"); # "c"
my $true_or_false = /\w+/g; # 1 or ""
my $dunno = some_function(); # who knows?!
The last example is particularly nasty: the return value of the function will be evaluated in scalar context. If that value is @array
, then you'll get the size of the array; if it's @array[0,1]
, you'll get $array
So how does the empty parentheses idiom work? It uses a little-exercised rule: a list assignment in scalar context returns the number of elements on the right-hand side of the list assignment. That's probably also rarely-spoken, since it's a bit dense. What it means is that an expression like (LIST1) = (LIST2), in scalar context, returns the number of elements in LIST2 (not LIST1). This means (LIST1) could be replaced with () and the scalar value returned would still be the size of LIST2.
This trick is most frequently used in conjunction with a regex with the "global" switch on it. In scalar context, such a regex would only match once, but in list context, it matches exhaustively. To get all such matches, one would do @matches = /.../g. But if we aren't interested in keeping the matches around, and instead just want to know how many there are, we could replace @matches with (), and evaluate it all in scalar context: my $count = (() = /.../g);. Of course, those outer parentheses are unnecessary, so the idiom becomes my $count = () = /.../g;.
It forces an expression to be evaluated in list context, and returns the number of elements returned by that expression.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
Outside of code tags, you may need to use entities for some characters:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||