Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: using if-elsif-else

by chargrill (Parson)
on Dec 28, 2006 at 15:46 UTC ( #592068=note: print w/replies, xml ) Need Help??


in reply to using if-elsif-else

Hello thevoid,

You're fairly close - you just have the syntax a bit off.

The general structure is this:

if ( condition ){ # code } elsif ( condition ){ # code } else { # default case, in case no conditions match }

So your code should look like this:

#!/usr/bin/perl #hash.plx use warnings; use strict; my %phnums = ( derrick => '07786255633', juan => '07798685311', kevin => '07740647707', ); print "Enter a name : "; my $name = <STDIN>; chomp ($name); if ($name =~ /^derrick\b/i) { print $phnums{"derrick"}; } elsif ($name =~ /^juan\b/i) { print $phnums{"juan"}; } else { print $phnums{"kevin"}; }

Note, if you enter "fred", you'll see Kevin's number. So you might instead want:

#!/usr/bin/perl #hash.plx use warnings; use strict; my %phnums = ( derrick => '07786255633', juan => '07798685311', kevin => '07740647707', ); print "Enter a name : "; my $name = <STDIN>; chomp ($name); if ($name =~ /^derrick\b/i) { print $phnums{"derrick"}; } elsif ($name =~ /^juan\b/i) { print $phnums{"juan"}; } elsif ($name =~ /^kevin\b/i) { print $phnums{"kevin"}; } else { print "Name not found."; }


--chargrill
s**lil*; $*=join'',sort split q**; s;.*;grr; &&s+(.(.)).+$2$1+; $; = qq-$_-;s,.*,ahc,;$,.=chop for split q,,,reverse;print for($,,$;,$*,$/)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2019-09-21 03:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The room is dark, and your next move is ...












    Results (269 votes). Check out past polls.

    Notices?