- Assignment Operators
- Increment and Decrement Operators
- String Concatenation and Repetition
- Operator Precedence and Associativity
- Using Patterns to Match Digits
- An Example: Simple Statistics
- Input and Output
- Another Example: Stocks
- A Note About Using Functions
- Going Deeper
- Summary
- Q&A
- Workshop
- Answers
A Note About Using Functions
Now that you've learned about the print and chomp functions, as well as had a glimpse of other functions such as int and sprintf, this is a good time to go over how function calls work. If you've been paying careful attention, you might have noticed that I've been calling the print function like this:
print "Hello, World!\n";
I've also been calling chomp and printf like this:
chomp($input = <STDIN>); printf("Average (mean): %.2f", $avg);
One form has parentheses around the arguments to the function, the other form doesn't. Which is correct? The answer is both. Parentheses around the arguments to a function are optional; as long as Perl can figure out what your arguments are, either form works just fine.
In this book, I've used a smattering of both. My general rule is that if a function takes one argumentint or oct being good examplesI'll leave off the parentheses. If it takes multiple arguments or if its argument is an expression (printf or chomp), then I use parentheses. The print function can go either way depending on the situation.
Depending on what you're familiar withand what looks right to youfeel free to pick your own rule for parenthesizing functions in your own scripts. I should mention, however, that the rule of parentheses being optional "as long as Perl can figure out what your arguments are," can occasionally be tricky to figure out, particularly with multiple arguments and when some of them are parenthesized expressions or lists. To make it even more complex, some of Perl's built-in functions are actually operators, and have a different precedence from actual function calls. (see the next section, "Going Deeper," for more information). There are rules of precedence to determine exactly how complex function calls are to be evaluated, but the safest solution, if Perl appears to be ignoring your arguments or producing weird results, is to include parentheses around all the arguments. Turning on Perl warnings will also help catch some of these problems.