One way, albeit not pretty, is to form a closure | lexical closure (if that's the proper terminology) over the value of the global $_ and use the closed-over value:

Win8 Strawberry 5.8.9.5 (32) Sat 05/08/2021 0:53:55 C:\@Work\Perl\monks >perl use strict; use warnings; my %dispatch = ( normal => sub{"$_[0] Normal dispatch"}, map { my $__ = $_; $_ => sub{"$_[0] Sub returns $__"} } qw| Uno Dos tres| ); print $dispatch{"normal"}->(0),"\n"; # 0 Normal dispatch (as expected +) print $dispatch{"Uno"} ->(1),"\n"; # WANT: "1 Sub returns Uno" print $dispatch{"Dos"} ->(2),"\n"; # WANT: "2 Sub returns Dos" ^Z 0 Normal dispatch 1 Sub returns Uno 2 Sub returns Dos

Update 1: Also see this article on closure.

Update 2: Another way, not involving closures - although closures are not to be scorned!

Win8 Strawberry 5.8.9.5 (32) Mon 05/10/2021 9:33:38 C:\@Work\Perl\monks >perl use strict; use warnings; my %dispatch = ( normal => sub{ "$_[0] Normal dispatch" }, map { $_ => eval qq{ sub{ "$_ returns \$_[0]" } } } qw(Uno Dos tre +s), ); print $dispatch{'normal'}->( 0), "\n"; print $dispatch{'Uno' }->( 1), "\n"; print $dispatch{'Dos' }->( 22), "\n"; print $dispatch{'tres' }->(333), "\n"; ^Z 0 Normal dispatch Uno returns 1 Dos returns 22 tres returns 333


Give a man a fish:  <%-{-{-{-<


In reply to Re: Attempting to use $_ in "sub" inside "map" (updated) by AnomalousMonk
in thread Attempting to use $_ in "sub" inside "map" by NetWallah

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, 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, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.