http://www.perlmonks.org?node_id=686383

tford has asked for the wisdom of the Perl Monks concerning the following question:

I'm working on lexing mathematical expressions and I'm constructing a toy example of a non-deterministic finite automaton.

I've decided that the transition tables should be stored in hashes so that input characters can actually serve as keys to the hash. It is possible that some inputs may map to more than one transition, so I've also decided that each key (input character) should have a reference to an anonymous array as its value. If the input character only specifies one transition, then the value should be a reference to an array containing only one element!

This way of thinking produces some states with pretty boring transition tables. For example, a state that represents the situation of "about to read an identifier," which I've called 'id_0', might have a transition table which looks like the following.

id_0 => {a=>['id_1'], b=>['id_1'], . . . z=>['id_1']}

Now, in my toy example, I've constructed this state using the following technique.

use strict; use warnings; my @array = ('a'..'z'); my %hash = map {$_ => ['id_1']} @array; my $hashref = \%hash; my %states = (id_0 => $hashref); print("The first transition for (state,input) pair (id_0,x) is\n"); print($states{id_0}->{x}->[0]);

My question is, "Is there a way to do this without the intermediate %hash variable?"

Any help will be appreciated, whether it's a "Here's how you do it" one liner, or a "Why do you want to it that way, when you could do it this way" type of thing.

~T