in reply to (lestrrat) Re: Trying to simulate a CLI using hashes...
in thread Trying to simulate a CLI using hashes...

Hmmm, when I try to create a hash similar to the one that you suggested, it just runs the routines...I am new to perl, so I'm not sure if I typed something in wrong or not. Program outputs Welcome Ending Program Died at..... I must have mis-understood what you were trying to explain with the hash.
use strict; my $input; my %commands; my $cmd; my %commands = ( greeting => \&greeting(), quit => \&end_program(), ); chomp( $input = <STDIN> ); my( $cmd, @args ) = split( /\s+/, $input ); if( defined( $commands{ $cmd } ) ) { $commands{ $cmd }->( @args ); } sub greeting { print "Weclome\n"; } sub end_program { print("Ending Program\n"); die; }

Replies are listed 'Best First'.
Re: Re: (lestrrat) Re: Trying to simulate a CLI using hashes...
by lestrrat (Deacon) on Jan 22, 2002 at 07:36 UTC

    No no, don't put them parathesis! That makes perl evaluate the subroutine, and put the ref to the result of the sub in the hash

    my $rv = mysub(); ## sub is executed. normal my $rv = &mysyb(); ## same as above, but bad style, I think my $rv = \&mysub; ## ref to the subroutine <- this is what we +want my $rv = \&mysub(); ## ref to the return value of the subroutine my $rv = \{ &mysub() }; ## same as above

    UPDATE: wog corrected me: "\{ &mysub() } creates a reference to a refrence to a hash generated from mysub() returns in list context,". I apologize for the mistake :-(