Try something like this, which is 'use strict'-clean:
sub cmd_move { my ($package, $direction) = @_; print "You start to walk $direction, but suddenly remember that Gr +ues live there\n"; } while (<STDIN>) { chomp; my ($cmd, @args) = split(/\s+/, $_); $cmd = "cmd_$cmd"; if (($cmd !~ /^\w+$/) || !main->can($cmd)) { print "Unknown command. Try again.\n"; } else { main->$cmd(@args); } }
The trick is that all commands defined in the top-level are considered to be in the package 'main', and any package can be treated as a class. Hence main->can($x) will tell you whether there is a method named $x in package main, and main->$x() will call it (and pass in the string 'main' as the first argument.)

You might also want to use __PACKAGE__ instead of main, so that this will work even if you implement it inside of another package. But even better, define all of your commands in a different package just to make extra sure you don't accidentally expose a regular subroutine to the user:

package Commands; sub cmd_move {....}; . . . package main; while (<STDIN>) { ... if (Commands->can($cmd)) {...} }
Just to be avoid confusion, I prefix cmd_ to the names of the command subroutines, so that if the user types 'move' then the subroutine 'cmd_move' will be run. Also, I check to be sure the command looks valid. The command is never evaluated or substituted into an external system call or anything, so it doesn't really matter, but you should probably do it anyway just in case you start to use it differently later.

In reply to Re: Naming Subs by sfink
in thread Naming Subs by eoin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.