in reply to elsif failing
using:
at the top of each program saves you a lot of trouble, notice, when the strictures are on you would have to declare your variables using "my" the first time the variable is brought to existence, this has got to do with proper scoping and serves also to save you headaches from typing errors in variable namesuse strict; use warnings;
Now here is how your program would look like after corrections. Notice I did not use escaping by \n to put an apostrophe in you're because it is (i.e ' ) not one of Perl's metacharacters.
Just like GrandFather said, using a data structure like hashes is the answer to avoid repetitive code-writing. Another thing, Perl boasts of a capability called TIM TOWDY which means "There is more than one way to do it", and here is another way to do your program in addition, using another type of data structures called arrays to hold the names for you and the rest of the code just checks the condition when the name exists and prints it:#!/usr/local/bin/perl use strict; use warnings; print "What is your name?\n"; chomp(my $name = <STDIN>); if ($name eq 'larry') { print "You're Larry!\n" } elsif ($name eq 'moe') { print "You're Moe!\n" } elsif ($name eq 'curly') { print "You're Curly!\n" }
Update: Hashes are more flexible to work with as GrandFather duly explained. I wish you a happy Perl programming, it is just real fun to learn Perl.#!/usr/local/bin/perl use strict; use warnings; my @names =qw(larry moe curly); print "What is your name\n"; chomp(my $name = <STDIN>); if(grep {/$name/} @names){ print "you're @{[grep {/$name/} @names]}!\n"; }else{ print "I don't know this name\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: elsif failing
by GrandFather (Saint) on Sep 22, 2009 at 07:11 UTC |