Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Rosetta Dispatch Table

by duelafn (Vicar)
on Nov 22, 2017 at 01:27 UTC ( #1203974=note: print w/replies, xml ) Need Help??


in reply to Rosetta Dispatch Table

I do like the hash for clean and obvious enumeration, but I hate the explicit hash and typing key names more than once, so I tend to hide both declaration and invocation in subs:

#!/usr/bin/perl -s use strict; use warnings; use 5.014; our $h; sub callback; our %CALLBACKS; # Callback functions --------------------------------------- callback first => sub { my $z = shift; print "in first_callback, z=$z\n"; return 1; }; callback last => sub { my $z = shift; print "in last_callback, z=$z\n"; return 2; }; # Implementation of dispatch table ------------------------- # (You need to write this code) sub callback { my ($name, $cb) = @_; $CALLBACKS{$name} = $cb; } sub invoker { my ($name, $z) = @_; return -1 unless exists($CALLBACKS{$name}); $CALLBACKS{$name}->($z); } sub help { say "Available callbacks: @{[ sort keys %CALLBACKS ]}"; } # Main program for testing --------------------------------- exit help() if $h; for my $name ( "first", "last", "fred" ) { my $rc = invoker( $name, $name . '-arg' ); print "$name: rc=$rc\n"; }

Results:

$ perl /tmp/1203952.pl -h Available callbacks: first last $ perl /tmp/1203952.pl in first_callback, z=first-arg first: rc=1 in last_callback, z=last-arg last: rc=2 fred: rc=-1

Good Day,
    Dean

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2021-03-02 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favorite kind of desktop background is:











    Results (41 votes). Check out past polls.

    Notices?