Skip to Main Content
Perl in a Nutshell, 2nd Edition
book

Perl in a Nutshell, 2nd Edition

by Nathan Patwardhan, Ellen Siever, Stephen Spainhour
June 2002
Beginner content levelBeginner
759 pages
80h 42m
English
O'Reilly Media, Inc.
Content preview from Perl in a Nutshell, 2nd Edition

Private and Local Variables

Any variables you use in the function that aren’t declared private are global variables. In subroutines, you’ll often want to use variables that won’t be used anywhere else in your program, and you don’t want them taking up memory when the subroutine is not being executed. You also might not want to alter variables in subroutines that might have the same name as global variables.

The my function declares variables that are lexically scoped within the subroutine. Lexically scoped variables are private variables that exist only within the block or subroutine in which they are declared. Outside of their scope, they are invisible and can’t be altered in any way.

To scope multiple variables at once, use a list in parentheses. You can also assign a variable in a my statement:

my @list = (44, 55, 66);
my $cd = "orb";

Dynamic variables are visible to other subroutines called from within their scope, are defined with local, and are not private variables but global variables with temporary values. When a subroutine is executed, the global value is hidden away, and the local value is used. Once the scope is exited, the original global value is used. Most of the time, you will want to use my to localize parameters in a subroutine.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl by Example, Fourth Edition

Perl by Example, Fourth Edition

Ellie Quigley
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington
Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 0596002416Errata Page