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)
For more fun, feel free to implement the above specification in another language of your choice.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.