The @{[]} is a trick to force list context. The reason why list context is important is because of what the regex operator returns. In list context, the regex operator returns a list of what is matched. In scalar context, the regex operator returns whether or not it matched. (In theory, that should be the number of things matched as well, but I couldn't get it to work.)
So, by forcing list context, I get the list of things matched. Then, by converting the list to scalar context, I get the number of things in the list.
I'm sure there's a more elegant way than creating two array references on the fly, but that's what I had in 60sec of imperfect memory.
------ We are the carpenters and bricklayers of the Information Age. Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement. | [reply] [d/l] |
The @{[]} is a trick to force list context.
Actually, it does a bit more than that. It creates an array. You could have forced list context simply by using parens but a list in scalar context would return the last element in the list rather than the number of elements. So, you did what you had to. :-)
-sauoq
"My two cents aren't worth a dime.";
| [reply] [d/l] |
| [reply] [d/l] |
To ensure that characters such as '^', '-' or ']' do not interfere, I would always be tempted to surround the interpolated value with \Q..\E.
An alternative (more intuitive?) method of forcing list context on an expression, is to assign the expression to a list:
my $count = () = $x =~ /[\Q$y\E]/g;
The comma operator in scalar context returns the second argument. The intermediate assignment above causes the comma operator to believe it is an list context.
UPDATE: chromatic beat me to the draw by 2 minutes on the ()= trick. However -- chromatic: you cannot claim credit for being the first to use this trick (chromatic's context chaining). I remember it from the time that it was being argued over on the perl5-porters mailing list, perhaps 5 years ago... :-)
| [reply] [d/l] |