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

Re: using if-elsif-else

by chargrill (Parson)
on Dec 28, 2006 at 15:46 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://592068]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-19 21:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found