The “goatse operator” or the =()= idiom in Perl causes an expression to be evaluated in list context.
An example is:
my $str = "5 and 4 and a 3 and 2 1 BLAST OFF!!!";
my $count =()= $str =~ /\d/g; # 5 matches...
print "There are $count numbers in your countdown...\n\n";
As I interprete the use, this is what happens:
$str =~ /\d/gmatches all the digits. Thegswitch and list context produces a list of those matches. Let this be the “List Producer” example, and in Perl this could be many things.- the
=()=causes an assignment to an empty list, so all the actual matches are copied to an empty list. - The assignment in scalar context to $count of the list produced in 2. gives the count of the list or the result of 5.
- The reference count of the empty list
=()=goes to zero after the scalar assignment. The copy of the list elements is then deleted by Perl.
The questions on efficiency are these:
- Am I wrong in how I am parsing this?
- If you have some List Producer and all you are interested in is the count, is there a more efficient way to do this?
It works great with this trivial list, but what if the list was hundreds of thousands of matches? With this method you are producing a full copy of every match then deleting it just to count them.
Perl 5 is smart about copying lists. It only copies as many items as are on the left hand side. It works because list assignment in scalar context yields the number of items on the right hand side. So,
nitems will be created by the regex, but they won’t be copied and discarded, just discarded. You can see the difference the extra copy makes in the naive case in the benchmark below.As for efficiency, an iterative solution is often easier on memory and CPU usage, but this must be weighed against the succinctness of the goatse secret operator. Here are the results of benchmarking the various solutions:
Here is the code that generated it: