One neat thing you can play with is a hash-based dispatch table. The idea is you store code references as the hash values, and look up the code by key, as necessary.
Here's a simplistic example that hopefully gives you some idea of the power behind these constructs. Say you have a string of text, and you want to read it word-by-word, reacting to certain words in different ways. A traditional way to do that would be:
my $text = "I am going to walk to the park."; for ($text =~ /(\w+)/g) { if (lc $_ eq "walk") { print "Walking is good for you\n"; } elsif (lc $_ eq "park") { print "Parks are fun\n"; } }
That's good and well, but not very flexible, or scalable. Each new entry would require a new branch in the if/elsif chain, which can really start to add up. A hash-based approach might look something like this:
my %react_to = ( walk => sub { print "Walking is good for you\n" }, park => sub { print "Parks are fun\n" }, ); my $text = "I am going to walk to the park."; for ($text =~ /(\w+)/g) { if (my $reaction = $react_to{lc $_}) { $reaction->(); } }
This one may seem more complicated, but it's moving the logic out of a nested chain of if/elsif statements and into a data structure. All sorts of neat things can then be done with that data structure, including modifying it at runtime. Here's a dispatch table that modifies itself at runtime:
my %react_to = ( a => sub { shift->{b} = sub { print "A before B\n" } }, b => sub { shift->{a} = sub { print "B before A\n" } }, ); my $text = "b is the first word, but a is not the last."; for ($text =~ /(\w+)/g) { print "Read word: $_\n"; if (my $reaction = $react_to{$_}) { $reaction->(\%react_to); } }
This may be a contrived example, and it relies on the calling code passing the dispatch table in as an argument, but the idea is there.
In reply to Re: Mashing with Hashing
by revdiablo
in thread Mashing with Hashing
by hacker
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |