in reply to Re: elsif failing
in thread elsif failing
A more interesting 'nother way to do it' is by dispatching methods. It's still a hash lookup under the hood, but is a fine technique to be aware of for some situations (adding verbs to a parser for example). Consider:
use warnings; use strict; print "What is your name?\n"; chomp (my $name = ucfirst <STDIN>); my $obj = bless {}; my $call = $obj->can ("name$name"); if ($call) { $call->(); } else { print "I can't handle anyone by the name $name.\n"; } sub nameLarry { print "Hi Larry. Welcome\n"; } sub nameMoe { print "Hi Moe. Late again I see!\n"; } sub nameTim { print "Hi TIMTOWTDI. Still pursuing the alternative life style?\n" +; }
The OP should note that while using an array and grep is an alternative technique, it's not a very good alternative because it doesn't scale well. That is, if there are a lot of names and the lookup needs to be done many times the 'linear search' that grep uses will slow processing down substantially. A small improvement can be made by using a for loop and using last to exit the loop as soon as a match is found, but that really doesn't redeem the array lookup where a hash or method dispatch could have been used.
|
|---|