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:
#!/usr/bin/perl -w use strict; my %number_to_word = ( 1 => 'one', 2 => 'two', 3 => 'three', ); my @numbers = qw(1 2 3 4); foreach my $number (@numbers) { print "My number is ", $number_to_word{$number} || 'four', "\n"; }
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 reply to (dkubb) Re: (2) Using array elements as subroutine args
by dkubb
in thread Using array elements as subroutine args
by Tuna
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |