in reply to Regex - Matching prefixes of a word

I'd isolate the first "word" the player gives, and then check if it's a prefix. For instance:
my ($first) = /^\s*(\w+)/ or next; if (index $first, "hello") { ... whatever ... }
But if there's a limited number of commands a player can give, I would pre-calculate all unique prefixes, store them in a hash (with the real word as value), and then just do the hash access. For instance:
my %prefixes = calc_all_unique_prefixes; if (/my ($first) = /^\s*(\w+)/) { if (exists $prefixes{$first}) { do_command $prefixes{$first} } else { print "What?\n"; } }

Replies are listed 'Best First'.
Re^2: Regex - Matching prefixes of a word
by SuicideJunkie (Vicar) on Jul 24, 2009 at 17:23 UTC

    A slight variation on that would be to have the hash indicate what to do rather than just what the word is. Split the command into words, and then follow the hash references to decide what to do, until you reach a code reference, or a !exists (indicating success or invalid command). It could be combined with the backwards regex trick, or the automatic regex generation to avoid having to list all substrings.

    One challenge with that approach is how to deal with optional fields and variable length lists of parameters. I suppose that line of thought could quickly turn the project into a full LR parser / evaluator.