10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

APPENDIX ■ PERL BASICS 315Now we get the right result:$ perl varint4.plThis is the 8th time.$The if StatementIn programming, we often need <strong>to</strong> test a condition, and if that condition is true, take someaction. This can be performed using an if statement, which has the general syntaxif ( condition ) {statements}Don’t type this in and try <strong>to</strong> make it run—it is meant <strong>to</strong> be a general structure of the construct.An important note: those curly braces around the body (the statements) are required. Youmust use them, even if the body is one line of code.For instance, let’s say we want <strong>to</strong> divide by a number unless that number is 0. We can firstcheck <strong>to</strong> see if the number is not 0, and if it is not, perform the division.if ($number != 0) {$result = 100 / $number;}Let’s create a program <strong>to</strong> use the if statement. It will prompt the user <strong>to</strong> enter a number.If the number is not 0, then 100 is divided by that number and the result is s<strong>to</strong>red in $result. Ifthe number is 0, the result will remain the default value of 0:#!/usr/bin/perl -w# if.pluse strict;print "please enter a number: ";chomp(my $number = );my $result = 0;if ($number != 0) {$result = 100 / $number;}print "the result is: $result\ n";Recall that the statementchomp(my $number = );

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!