in reply to beginner scripting question re: if elsif else
My guess is that you mean you want execution to stop before your get to question #2. In order for that to hold, you need to test the value of $weather before your execute your next print. Perhaps you mean something more like:
If you want to avoid explicit exits, you could do the same thing with nested if-elsif-else's:#!/usr/bin/perl # walkies.pl use warnings; use strict; print "What's the weather like outside? "; chomp(my $weather = <STDIN>); if ($weather eq "snowing") { print "OK, let's go!\n"; exit; } elsif ($weather eq "raining") { print "No way, sorry, I'm staying in.\n"; exit; } print "How hot is it, in degrees Celsius? "; my $temperature = <STDIN>; if ($temperature < 18) { print "Too cold for me!\n"; exit; } print "And how many emails left to reply to? "; my $work = <STDIN>; if ($work > 30) { print "Sorry - just too busy.\n"; } else { print "Well, why not?\n"; }
#!/usr/bin/perl # walkies.pl use warnings; use strict; print "What's the weather like outside? "; chomp(my $weather = <STDIN>); if ($weather eq "snowing") { print "OK, let's go!\n"; } elsif ($weather eq "raining") { print "No way, sorry, I'm staying in.\n"; } else { print "How hot is it, in degrees Celsius? "; my $temperature = <STDIN>; if ($temperature < 18) { print "Too cold for me!\n"; } else { print "And how many emails left to reply to? "; my $work = <STDIN>; if ($work > 30) { print "Sorry - just too busy.\n"; } else { print "Well, why not?\n"; } } }
There are a multitude of other ways to do this, but it all comes down to thinking about the logical progression of what you want to accomplish.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: beginner scripting question re: if elsif else
by jhumphreys (Novice) on Oct 11, 2012 at 21:08 UTC | |
by Dlamini (Novice) on Oct 11, 2012 at 21:17 UTC | |
by jhumphreys (Novice) on Oct 11, 2012 at 21:28 UTC |
In Section
Seekers of Perl Wisdom