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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.