next up previous contents
Next: String Functions Up: Functions Previous: Nesting Function Calls

Using a Private Function

Occasionally, you might want to create a private function. A private function is one that is only available inside the scope where it was defined,

$temp = performCalc(10, 10);

print("temp = $temp\n");

sub performCalc {

    my ($firstVar, $secondVar) = @_;

    my $square = sub {

        return($_[0] ** 2);


    return(&$square($firstVar) + &$square($secondVar));


This program prints:

temp = 200

This example is rather trivial, but it serves to show that in Perl it pays to create little helper routines. A fine line needs to be drawn between what should be included as a private function and what shouldn't. I would draw the line at 5 or 6 lines of code. Anything longer probably should be made into its own function. I would also say that a private function should have only one purpose for existence. Performing a calculation and then opening a file is too much functionality for a single private function to have.

The rest of the chapter is devoted to showing you some of the built-in functions of Perl. These little nuggets of functionality will become part of your arsenal of programming weapons.