Front page | perl.beginners |
Postings from April 2010
about dispatch tables
Thread Previous
|
Thread Next
From:
Harry Putnam
Date:
April 23, 2010 19:40
Subject:
about dispatch tables
Message ID:
87y6gdindz.fsf@newsguy.com
A while ago I asked for an example of a dispatch table.
rkb@i.frys.com was kind enough to post the example below.
After tinkering with it a while I think I got it working ok, but I
wondered when you are using the reference syntax \&... How do you
pass in variables? My test script posted below the example dispatch
table doesn't get it right.
------- --------- ---=--- --------- --------
From: rkb@i.frys.com
Subject: Re: Nested if and elsif and else
Newsgroups: gmane.comp.lang.perl.beginners
To: "Harry Putnam" <reader@newsguy.com>
Date: Thu, 15 Apr 2010 09:02:39 -0700
Message-ID: <a2481e9b1000047d45e4e8f89a168623.squirrel@webmail.i.frys.com>
[...]
Here's an example I gave in a similar question in another
forum.
my %dispatch = (
1 => \&getcpuinfo,
2 => \&osversion,
3 => \&loadaverages,
4 => \&systemload_uptime,
5 => \&netinterfaceinfo,
6 => \&diskusage,
7 => \&ipaddress,
q => sub { print "Goodbye\n" and exit; },
error => sub { print "invalid selection\n" },
);
while(1)
{
print "press 1 to get CPU Info \n",
"press 2 to get OS version \n",
"press 3 to get CPU Load averages\n",
"press 4 to get System Load & Uptime\n",
"press 5 to get Net Interface info\n",
"press 6 to get system disk usage info \n",
"press 7 to get IP address info \n";
"press q to Exit\n"
chomp(my $selection) = <STDIN>;
my $code = $dispatch{$selection} || $dispatch{'error'} ;
$code->();
}
------- --------- ---=--- --------- --------
Trying to pass variables into one of the referenced sub routines like
7 => \&ipaddress($var1,$var2);
Is apparently not the way to do it. My silly test script below shows this
output when I press run ./dispatch and press `y':
press y
press n
press q to Exit
y
Not a CODE reference at ./dispatch line 33, <STDIN> line 1.
------- --------- ---=--- --------- --------
#!/usr/local/bin/perl
use strict;
use warnings;
my $var1 = 'whoopdee';
my $var2 = 'do';
my %dispatch = (
y => \&yy($var1,$var2),
n => sub { print "You pressed \`n' \n";},
q => sub { print "Goodbye\n" and exit;},
error => sub { print "invalid selection\n" }
);
while(1)
{
print "press y \n",
"press n \n",
"press q to Exit\n";
chomp(my $selection = <STDIN>);
my $code = $dispatch{$selection} || $dispatch{'error'} ;
$code->();
}
sub yy {
my ($var1,$var2);
($var1,$var2) = (shift,shift);
my $retstr = sprintf "You pressed \`y',$var1 $var2 .. but why?\n";
return $retstr;
}
Thread Previous
|
Thread Next