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: <%-{-{-{-<