in reply to Trying to simulate a CLI using hashes...

Well, first off, why don't you just make you orignal hash something like this:

my %commands = ( cmd1 => \&do_cmd1, cmd2 => \&do_cmd2, .... );

This buys you the flexibility of passing arguments to the subs, if you so wish to

## untested, just something I thought up right now chomp( $input = <STDIN> ); my( $cmd, @args ) = split( /\s+/, $input ); if( defined( $commands{ $cmd } ) ) { $command{ $cmd }->( @args ); }

Obviously you would need to do more error checking and what not, but you get the idea. Also, if you might want to try useing Term::ReadLine and its related modules for soemthing like this. It's quite handy

Replies are listed 'Best First'.
Re: (lestrrat) Re: Trying to simulate a CLI using hashes...
by thoth (Novice) on Jan 22, 2002 at 07:08 UTC
    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; }

      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 :-(