title: How can I distinguish $_ in nested list operators in Perl?
body: <p>It is often useful to implement algorithms using nested array operations. For example, to find the number of words in a list that start with each given character, you might do something like this in Python:</p>
  
  <pre><code>&gt;&gt;&gt; a = ["foo","bar","baz"]
  &gt;&gt;&gt; map(lambda c: len(filter(lambda w: w.startswith(c), a)), ('a','b','c','d','e','f'))
  [0, 2, 0, 0, 0, 1]
  </code></pre>
  
  <p>In the expression <code>w.startswith(c)</code> it is trivial to distinguish between the two loop iteration variables <code>w</code> and <code>c</code> because they have different names.</p>
  
  <p>In Perl, I would like to do something like this:</p>
  
  <pre><code>@a = ("foo", "bar", "baz");
  map length(grep $_ =~ /^$_/, @a), ('a','b','c','d','e','f')
  </code></pre>
  
  <p>However, the obvious problem with this is that <code>$_</code> refers only to the <em>innermost</em> <code>grep</code> iteration variable (suitable for the <code>$_</code> on the left), not the one for the outer <code>map</code> (suitable for the <code>/^$_/</code>). What is the idiomatic way to avoid this problem in Perl?</p>