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!
";

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 argument—int or oct being good examples—I'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 with—and what looks right to you—feel 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset