O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.5. Private Variables in Functions

We've already talked about the @_ variable and how a local copy gets created for each subroutine invoked with parameters. You can create your own scalar, array, and hash variables that work the same way. You do this with the my operator, which takes a list of variable names and creates local versions of them (or instantiations, if you like bigger words). Here's that add function again, this time using my:

sub add {
    my ($sum);           # make $sum a local variable
    $sum = 0;            # initialize the sum
    foreach $_ (@_) {
        $sum += $_;      # add each element
    }
    return $sum;            # last expression evaluated: sum of all elements
}

When the first body statement is executed, any current value of the global variable $sum is saved away, and a brand new variable named $sum is created (with the value undef). When the subroutine exits, Perl discards the local variable and restores the previous (global) value. This works even if the $sum variable is currently a local variable from another subroutine (a subroutine that invokes this one, or one that invokes one that invokes this one, and so on). Variables can have many nested local versions, although you can access only one at a time.

Here's a way to create a list of all the elements of an array greater than 100:

sub bigger_than_100 { my (@result); # temporary for holding the return value foreach $_ (@_) { # step through the arg list if ($_ > 100) { # is it eligible? push(@result,$_); # add it } } return @result; # return the final list ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required