Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Creating dispatch table with variable in function name

by stevieb (Canon)
on Nov 21, 2017 at 19:43 UTC ( [id://1203943]=note: print w/replies, xml ) Need Help??


in reply to Creating dispatch table with variable in function name

It "works" fine for me:

use warnings; use strict; use Data::Dumper; my %d = map { $_, \&{'create_' . $_} } qw(first); print Dumper \%d; $d{first}->(); sub create_first { print "first!\n"; }

Output:

$VAR1 = { 'first' => sub { "DUMMY" } }; first!

...so you need to describe what's not working as expected.

Are you wanting to call the sub like this?:

$dispatch{_create_first}->();

If so, you need to map the '_create_' to both arguments to map. This example uses a second map() to modify the $_ variable on the way into the map that creates the actual dispatch table.

use warnings; use strict; use Data::Dumper; my %d = map { $_, \&{$_} } map {'create_' . $_} qw(first); print Dumper \%d; $d{create_first}->(); sub create_first { print "first!\n"; }

Output:

$VAR1 = { 'create_first' => sub { "DUMMY" } }; first!

Replies are listed 'Best First'.
Re^2: Creating dispatch table with variable in function name
by nysus (Parson) on Nov 21, 2017 at 19:52 UTC

    Ugh, forgot the ->() bit to actually call the function. The sub { "DUMMY" } output when printing the variable was also throwing me off.

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

      Uf the sub { "DUMMY" } came from Data::Dumper, you can tell it to show the code by turning Deparse on:
      use Data::Dumper; $Data::Dumper::Deparse = 1; print Dumper(sub { $_[0] . $_[1] });

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1203943]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-26 03:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found