Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

(dkubb) Re: (2) Using array elements as subroutine args

by dkubb (Deacon)
on Feb 19, 2001 at 06:41 UTC ( [id://59324]=note: print w/replies, xml ) Need Help??


in reply to Using array elements as subroutine args

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://59324]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-19 14:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found