Welcome to the Monastery | |
PerlMonks |
(dkubb) Re: (2) Using array elements as subroutine argsby dkubb (Deacon) |
on Feb 19, 2001 at 06:41 UTC ( [id://59324]=note: print w/replies, xml ) | Need Help?? |
Tuna, it is possible to do what you want using something called a dispatch table. It's simply a hash, where the key is what you are searching for, and the value is what you want if you find an exact match for the key. Below is your example re-worked to use a dispatch table:
Please note that if $number isn't a match in %number_to_word, we'll default to printing four, using the || operator. This neatly covers your else condition. One big advantage of using a dispatch table over an if/elsif/else statement is that it's much simpler to add and debug new conditions that you were aware of during the initial design. Also, if you're looking to translate numbers to words you might want to check out the CPAN module Lingua::EN::Nums2Words. It has a method called num2word which can translate any number you supply to it into the corresponding english word.
In Section
Seekers of Perl Wisdom
|
|