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
-
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.
|