in reply to Re: Best way to handle 'commands'
in thread Best way to handle 'commands'

Ah marvellous. That's almost exactly what I was looking for.
Of course, most of the examples seem to use \&subroutine wheras I've been getting away with *subroutine. I'd imagine they are different, but can anyone enlighten me as to how? (and if what I'm doing is an example of wrongness, or just differentness...)
Update:After reading perlref, I get some of the idea.
--
It's not pessimism if there is a worse option, it's not paranoia when they are and it's not cynicism when you're right.

Replies are listed 'Best First'.
Re3: Best way to handle 'commands'
by blakem (Monsignor) on Sep 19, 2002 at 12:24 UTC
    *subroutine is actually a typeglob. Typeglobs harken back to the days of Perl 4, before references were around. In most normal situations you shouldn't need to use them now that we have real refs.

    What you've actually done is create an alias that refers to all "things" named 'refresh_list' That includes &refresh_list, $refresh_list, %refresh_list, @refresh_list, and a few more esoteric items.

    #!/usr/bin/perl -w use strict; use vars qw($refresh_list %refresh_list @refresh_list); %refresh_list = @refresh_list = 1..10; $refresh_list = 'Im a scalar'; sub refresh_list { return "Im a subroutine" }; my %command_list = ( 'update' => { args => 2, function => *refresh_list, }, ); print "Sub: " . &{ $command_list{update}{'function'} } . "\n"; print "Scalar: " . ${ $command_list{update}{'function'} } . "\n"; print "Hash: " . %{ $command_list{update}{'function'} } . "\n"; print "Array: " . @{ $command_list{update}{'function'} } . "\n"; __END__ Sub: Im a subroutine Scalar: Im a scalar Hash: 4/8 Array: 10

    -Blake

      One of the fun things about using typeglobs, is that you can use it to figure out which subs are defined in a given package. So, by doing something like this, you can skip the entire dispatch table(of course this wont work under use strict qw(refs);:

      for (@ARGV){ if(*{$_}{CODE}){ &{*{$_}}; } else { print STDERR "Dont know about $_\n"; } }

      Goldclaw