Harry Putnam wrote:
#!/usr/local/bin/perl

use strict;
use warnings;

my $var1 = 'whoopdee';
my $var2 = 'do';

my %dispatch = (
        y => \&yy($var1,$var2),
this, actually, is not a code reference but a return value reference of the &yy($var1, $var2) subroutine call, executed right at the time of %dispatch assignment. By using (...) after a subroutine name you have the subroutine executed and get its return value. Then, the leading '\' in this syntax makes a reference to that return value.

To see what has happened, try to run your code in debug mode (perl -d) and view the contents of your %dispatch hash, or place

use Data::Dumper;
print Dumper { %dispatch };

somewhere after %dispatch assignment. I saw the following:

$VAR1 = {
         'y' => \'You pressed `y\',whoopdee do .. but why?
',
         'n' => sub { "DUMMY" },
         'q' => sub { "DUMMY" },
         'error' => sub { "DUMMY" }
       };

        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->();
this is the place you really want to call your subroutine, so also the place to pass your arguments to it:

$code->($var1, $var2);

}

sub yy {
  my ($var1,$var2);
  ($var1,$var2) =  (shift,shift);
why not:

my ($var1, $var2) = @_;

or

my   $var1 = shift;
my   $var2 = 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