A while ago I asked for an example of a dispatch table.
r...@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: r...@i.frys.com
Subject: Re: Nested if and elsif and else
Newsgroups: gmane.comp.lang.perl.beginners
To: "Harry Putnam" <rea...@newsguy.com>
Date: Thu, 15 Apr 2010 09:02:39 -0700
Message-ID: <a2481e9b1000047d45e4e8f89a168623.squir...@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;
}


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to