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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

294APPENDIX ■ PERL BASICS#!/usr/bin/perl -w# arithop2.plprint "21 from 25 is: ", 25 - 21, "\ n";print "4 + 13 - 7 is: ", 4 + 13 - 7, "\ n";$ perl arithop2.pl21 from 25 is: 44 + 13 - 7 is: 10$Our next set of opera<strong>to</strong>rs (multiplying and dividing) is where it gets interesting. We usethe * and / opera<strong>to</strong>rs <strong>to</strong> multiply and divide, respectively.#!/usr/bin/perl -w# arithop3.plprint "7 times 15 is ", 7 * 15, "\ n";print "249 divided by 3 is ", 249 / 3, "\ n";The fun comes when you want <strong>to</strong> multiply something and then add something, or addand then divide. Here’s an example of the problem:#!/usr/bin/perl -w# arithop4.plprint 3 + 7 * 15, "\ n";This could mean one of two things: either <strong>Perl</strong> must add the 3 and the 7, and then multiplyby 15, or multiply 7 and 15 first, and then add. Which does <strong>Perl</strong> do? Try it and see . . .<strong>Perl</strong> should have given you 108, meaning it did the multiplication first. The order in which<strong>Perl</strong> performs operations is called opera<strong>to</strong>r precedence. Multiply and divide have a higherprecedence than add and subtract, and so they get performed first. We can start <strong>to</strong> draw upa list of precedence as follows:* /+ -To force <strong>Perl</strong> <strong>to</strong> perform an operation of lower precedence first, we need <strong>to</strong> use parentheses,like so:#!/usr/bin/perl -w# arithop5.plprint (3 + 7) * 15, "\ n";Unfortunately, if you run that, you’ll get a warning and 10 is printed. What happened? Theproblem is that print() is a function and the parentheses around 3 + 7 are treated as the onlyargument <strong>to</strong> print().

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

Saved successfully!

Ooh no, something went wrong!