start page | rating of books | rating of authors | reviews | copyrights

Book HomeLearning Perl, 3rd EditionSearch this book

4.6. Private Variables in Subroutines

But if Perl can give us a new @_ for every invocation, can't it give us variables for our own use as well? Of course it can.

By default, all variables in Perl are global variables; that is, they are accessable from every part of the program. But you can create private variables called lexical variables at any time with the my operator:

sub max {
  my($a, $b);       # new, private variables for this block
  ($a, $b) = @_;    # give names to the parameters
  if ($a > $b) { $a } else { $b }
}

These variables are private (or scoped) to the enclosing block; any other $a or $b is totally unaffected by these two. And that goes the other way, too -- no other code can access or modify these private variables, by accident or design.[108] So, we could drop this subroutine into any Perl program in the world and know that we wouldn't mess up that program's $a and $b (if any).[109]

[108]Advanced programmers will realize that a lexical variable may be accessible by reference from outside its scope, but never by name.

[109]Of course, if that program already had a subroutine called &max, we'd mess that up.

It's also worth pointing out that, inside the if's blocks, there's no semicolon needed after the return value expression. Although Perl allows for the last semicolon in a block to be omitted, in practice that's omitted only when the code is so simple that the block is written in a single line, like the previous ones.

The subroutine in the previous example could be made even simpler. Did you notice that the list ($a, $b) was written twice? That my operator can also be applied to a list of variables enclosed in parentheses, so it's more customary to combine those first two statements in the subroutine:

my($a, $b) = @_;  # Name the subroutine parameters

That one statement creates the private variables and sets their values, so the first parameter now has the easier-to-use name $a and the second has $b. Nearly every subroutine will start with a line much like that one, naming its parameters. When you see that line, you'll know that the subroutine expects two scalar parameters, which we'll call $a and $b inside the subroutine.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.