I’ve read tutorials and perldoc on map, tr and references, but this code is a little too advanced for a beginner Perl user like myself.
print map $_->[1],
sort {
$a->[0] cmp $b->[0] ##first element of the array
or $a->[1] cmp $b->[1] }
map [ tr/"MATCH"/"MATCH"/, $_ ], @allmatches;
So what I particularly need is: what $_ is referring to (undefined?)
The last line including map does what?
I don’t really understand the $a and $b concepts yet. What are they referring to? The first and next element of @allmatches?
Also, what do all the commas (after map) do? And if this is like a Schwartzian transform, good, because I don’t understand that yet, despite reading.
Here is my idea:
Maps undefined scalar as reference to an array(which?) simultaneously calling the second element: [1]. It sorts my @allmatches array first by amount of occurrences of “MATCH”‘s and then by alphabet. The second map by making a reference is rough for me (maps do a lot in one step); the tr returns number of times. The second “MATCH” is useless, but why?
Bonus: What could I replace tr/// with to sort by more, like if this was possible: tr/MATCH #\d+// ??
Reading it right-to-left (i.e., in the order it gets executed)…
For each element e of @allmatches, this creates a reference to a two-element array whose first element is a number and whose second element is e. The result of the map is an array of these references.
tr/"MATCH"/"MATCH"/is counting the number of times the letters M, A, T, C, or H occur in e. (It is technically replacing M by M, A by A, T by T, etc., and counting how many such replacements it made.)Actually, it is also counting quote characters, since tr/// is going to process those the same as anything else. This appears to be a bug.
Anyway, let’s say each of these references refers to an array [n,e], where n is the weird count and e is the original element of @allmatches.
The “sort” then sorts the array of references, primarily by n (interpreted as a string, not a number; this appears to be another bug) and secondarily by the string e.
Finally, the outermost “map” extracts the second element (e) from each of the two-element arrays after the sorting is done. So the final result is just to do a bizarre (and I believe, buggy) sort on the elements of @allmatches.
[Edit: As cjm points out in a comment, this
map sort mapidiom is called a Schwartzian transform.]