Ha ha, nysus just reminded me of an old interview question I used to ask. Implement a simple dispatch table.
Let's start with a specification:
- The key of the dispatch table is a string \w+
- The name of the callback function is the key name with _callback appended
- Each callback function takes a single string parameter and returns a positive number
You must write the invoker function, which takes two arguments (the name and the string argument to be passed to the callback):
- If the name is invalid (e.g. "fred" below), invoker must return a negative number
- Otherwise, invoker must pass its second argument to the callback function and return what the callback function returns
To clarify, here is a sample implementation.
use strict; use warnings; # Callback functions --------------------------------------- sub first_callback { my $z = shift; print "in first_callback, z=$z\n"; return 1; } sub last_callback { my $z = shift; print "in last_callback, z=$z\n"; return 2; } # Implementation of dispatch table ------------------------- # (You need to write this code) my %op_table = ( first => \&first_callback, last => \&last_callback, ); sub invoker { my ($name, $z) = @_; exists($op_table{$name}) or return -1; $op_table{$name}->($z); } # Main program for testing --------------------------------- for my $name ( "first", "last", "fred" ) { my $rc = invoker( $name, $name . '-arg' ); print "$name: rc=$rc\n"; }
Running the above test program produces:
in first_callback, z=first-arg first: rc=1 in last_callback, z=last-arg last: rc=2 fred: rc=-1
Points to consider:
- Is a hash the recommended way to implement a dispatch table in Perl?
- How many other ways can you think of to implement it in Perl? (working demonstration code would be good)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Rosetta Dispatch Table
by tybalt89 (Monsignor) on Nov 21, 2017 at 23:07 UTC | |
by eyepopslikeamosquito (Archbishop) on Nov 21, 2017 at 23:29 UTC | |
by LanX (Saint) on Nov 22, 2017 at 16:53 UTC | |
by tybalt89 (Monsignor) on Nov 26, 2017 at 18:45 UTC | |
by LanX (Saint) on Nov 26, 2017 at 20:36 UTC | |
by shmem (Chancellor) on Nov 26, 2017 at 19:26 UTC | |
by LanX (Saint) on Nov 26, 2017 at 18:54 UTC | |
Re: Rosetta Dispatch Table
by Limbic~Region (Chancellor) on Nov 22, 2017 at 13:57 UTC | |
Re: Rosetta Dispatch Table
by Eily (Monsignor) on Nov 22, 2017 at 17:45 UTC | |
by Eily (Monsignor) on Nov 22, 2017 at 18:31 UTC | |
Re: Rosetta Dispatch Table
by eyepopslikeamosquito (Archbishop) on Nov 22, 2017 at 22:59 UTC | |
Re: Rosetta Dispatch Table
by duelafn (Parson) on Nov 22, 2017 at 01:27 UTC | |
A reply falls below the community's threshold of quality. You may see it by logging in. | |
A reply falls below the community's threshold of quality. You may see it by logging in. |
Back to
Meditations