in reply to using if-elsif-else

BTW, if the theme of the example code is hash value access, you would not use the if-elsif-else clause in that manner, which could be, imho, confusing for beginners - it is not using hash in the most typical way. I think then following pice of code is slightly better for demonstration:
... chomp ($name); if (exists $phnums{$name}) { print $phnums{$name}; } else { print "Name $name does not exists in the hash."; }

Replies are listed 'Best First'.
Re^2: using if-elsif-else
by chargrill (Parson) on Dec 29, 2006 at 04:43 UTC

    I was operating under the assumption that a user could enter "Kevin Johnson" and still get the value for $phnums{'kevin'} - i.e. more than what might be used as the explicit hash key. Possibly a poor assumption, but I couldn't think of a better reason for using regexen in the OP's code :-)

    I recently ran across a hash setup as a dispatch table where most values were well defined, but some could match a variety - these were handled (in a generalized manner) like so:

    if( exists $hash{$key} ){ &$hash{$key}; } elsif( $key =~ /phrase/ ){ # several could match but all required the same action &$hash{'some_action'}; } else { &$hash{'default_action'}; }


    --chargrill
    s**lil*; $*=join'',sort split q**; s;.*;grr; &&s+(.(.)).+$2$1+; $; = qq-$_-;s,.*,ahc,;$,.=chop for split q,,,reverse;print for($,,$;,$*,$/)
      I was operating under the assumption that a user could enter "Kevin Johnson" and still get the value for $phnums{'kevin'} - i.e. more than what might be used as the explicit hash key.

      You're right, that was the idea :-) Thanks for the alternative code.

Re^2: using if-elsif-else
by thevoid (Scribe) on Dec 28, 2006 at 16:07 UTC
    Ah, nice one. I hadn't really covered exists yet but had seen it mentioned, that makes sense.