Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Attempting to use $_ in "sub" inside "map"

by NetWallah (Canon)
on May 08, 2021 at 04:36 UTC ( [id://11132259]=perlquestion: print w/replies, xml ) Need Help??

NetWallah has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to automate building a dispatch table - or at least, to minimize keystrokes.

Please suggest ways to achieve the desired result:

use strict; use warnings; my %dispatch = ( normal => sub{"$_[0] Normal dispatch"}, map( {$_ => 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"
This currently prints:
0 Normal dispatch Use of uninitialized value $_ in concatenation (.) or string at .\test +dispatch.pl line 5. 1 Sub returns Use of uninitialized value $_ in concatenation (.) or string at .\test +dispatch.pl line 5. 2 Sub returns
Also - is there a NAME for what I am attempting ? "Early evaluation of $_" ?

                "Avoid strange women and temporary variables."

Replies are listed 'Best First'.
Re: Attempting to use $_ in "sub" inside "map" (updated)
by AnomalousMonk (Archbishop) on May 08, 2021 at 05:02 UTC

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

      Thank you (++)! - that works well.

                      "Avoid strange women and temporary variables."

      > is to form a closure | lexical closure (if that's the proper terminology)

      I'm pretty sure both are correct. I have trouble to imagine closed over variables which are not lexical. (I usually call those global ;-)

      Personally I'd use "lexical closure" to disambiguate, if there is another interpretation of "closure" in the context.

      The same way we use "file-glob" and "type-glob" to distinguish between glob and the * sigil

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

        I have trouble to imagine closed over variables which are not lexical.

        Yeah, I was thinking about it after posting and I couldn't come up with an example of non-lexical closure either. I'll just add a link to the Wikipedia article and let everyone else figure it out. :)


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

        In languages without lexically scoped variables or something approximating them, there's not really any such thing as a closure. You can still have first-class functions (i.e. coderefs); they just have no need to close over anything.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11132259]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-25 10:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found