Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^2: Rosetta Dispatch Table

by Eily (Monsignor)
on Nov 22, 2017 at 18:31 UTC ( [id://1204055]=note: print w/replies, xml ) Need Help??


in reply to Re: Rosetta Dispatch Table
in thread Rosetta Dispatch Table (Interview Question)

Bonus (got the idea by reading tybalt89's version)

sub Invoker::first { shift; &first_callback } sub Invoker::last { shift; &last_callback } sub Invoker::AUTOLOAD { -1 } sub invoker { my $name = shift; Invoker->$name(@_); }
It looks and kind of quacks like a symbolic ref on the method name, except it works under strict and warnings.

Edit: Actually if you ignore the first parameter of the callbacks, you can just use the symbols table as the containing hash and use the method above :)

use strict; use warnings; # Callback functions --------------------------------------- sub first_callback { my (undef, $z) = @_; print "in first_callback, z=$z\n"; return 1; } sub last_callback { my (undef, $z) = @_; print "in last_callback, z=$z\n"; return 2; } sub default_callback { -1 } # Dispatch ------------------------------------------------- %Dispatch:: = ( first => *first_callback, start => *first_callback, last => *last_callback, AUTOLOAD => *default_callback); sub invoker { my $name = shift; Dispatch->$name(@_); } # Main program for testing --------------------------------- for my $name ( qw< first start last fred > ) { my $rc = invoker( $name, $name . '-arg' ); print "$name: rc=$rc\n"; }

Log In?
Username:
Password:

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

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

    No recent polls found