Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Perl namespaces

 News

Perl Language

Recommended Links Recommended Articles Perl programming environment Debugging Perl for Win32

Perl Warts

Perl Programming Environment Perl as a command line utility tool Perl modules Pipes in Perl Reimplementation of Unix tools      

Namespaces and Modules

grep & map

Sort

Networking

Tips Beautifiers Humor Etc
 

Introduction

The main problem in writing large programs is:

This is a critical part of programming language design and success of OO concept by-and-large was connected with built-in hierarchical namespaces model the OO provides.

One interesting feature of Perl is that unlike other languages it has an explicit concept of namespaces. Each namespace defines a separate symbol table, which is basically a hash with a key for each identifier. In other words in Perl you can have as many user-defined symbol tables as you wish (as many as the number of package statements you use). They are the instrument to segregate code so that one piece of code does not conflict with another.

Each new namespace is defined by package statement. It is active until the next package statement. If there is no package statement all variables belong to namespace main (global namespace).

Namespaces allow you segregate variables and functions into different folders like files in Unix filesystem. In other words they play the role similar to the role of directories in Unix system where full path for the file distinguishes it from the file with the same name but located in different directory. Variables in different namespaces can even have the same name, but they are completely distinct from one another. Namespaces hold only "global" (for a given namespace) variables names, my variables names that have lexical scope of a block are held separately.

A symbol table in Perl is implemented as a hash that holds all of the names defined in a namespace. All of the variable and function names belong to some symbol table (namespace). The hash for each namespace is named after the namespace with two colons. For example, the symbol table for the namespace utils is called %utils::.

That means that you can to access them from your program with regular means of accessing hashes. For example:

DB<3> foreach $s (keys %main::) { print "$s\n"}
version::
tag_start
chunk_insertion_date
tag_exists
date_start
found_news_section
Devel::
extract_h4_timestamp
crc32
h4_timestamp_end
global_h4
DIFF
Regexp::
dirs_visited
^
top_severity
UNIVERSAL::
Tk::
title
overload::
BASE
author
all
dir
detag

If you want to address a variable in other namespace that the current you need to provide "full path" alike addressing Unix files. For example tp access subroutine put_message from namespace utils you need to write:

&utils::put_message("this is warning");

Here we call the function put_message from the namespace utils. In using Unix filesystem terms it would be a file put_message in the directory /utils while in Perl this is symbol put_message in the namespace utils.

In Perl each new namespace is defined by package statement which is a compile time statement as it is influence the construction of symbol table which is compile-time activity.

Main namespace

The main namespace in Perl is called main:: . It is used for all variables as a default if no namespace statement exists. To access variables from all other namespace in the main namespace require qualification with the namespace name if they are accessed outside the scope of package statement which defines this namespace. You can export variable from other named namespaces into main:: so that you can use them without qualification by the namespace name.

The global namespace main:: contains many special variables (such as $_ or %ENV) which are automatically visible from all packages. Some other special variables, such as @INC, $AUTOLOAD, or $a and $b in a sort block also are global in nature and belong to the main namespace by default. @INC and %INC are built-in variables that define the list of directories were library or module will be searched for loading with use or require statements

Non default namespaces. Package statement

Each new namespace with the exception of default (main::) is introduced by package statement. It has just one argument: package name. By convention, package names start with a capital letter, and you should follow that convention when you create your own packages. The scope of a package statement is from the this statement to the next package statement at the same level of nesting or the end of the innermost enclosing block.

The term package is described in "Programming Perl" as:

A quantity of code that values its privacy, and tries to keep other code from trespassing upon its namespace by fencing all of its private belongings (variables and subroutines) into its own area. A variable or subroutine mentioned in the package belongs only to that package, even if there's another variable or subroutine with an identical name in some other package.

All identifiers located with the scope of package declaration belong to the namespace declared in the package statement. They will be placed in the symbol table with this name.

Packages may be nested inside other packages. However, the package name must still be fully qualified. For example, if the package Province is declared inside the package Nation, a variable in the Province package is called as $Nation::Province::var. You cannot use a "relative" package name such as $Province::var within the Nation package for the same thing.

The default main namespace contains all other packages within it.

There is a very readable description of namespaces and typeglobs in Chapter 3 of "Advanced Perl Programming." It is worth reading for no other reason that to understand how Perl keeps track of scalars, arrays, etc. internally. The author uses graphics in his explanations. It also fully explains the difference between dynamic ('local') and lexical ('my') scoping of variables.

You can put a package declaration anywhere you can put a statement. Again, it is very important to understand that this is a compile time statement. You can also switch back into previous namespace in more than one place; package statement merely determines which symbol table is used by the compiler for the rest of that block.

That means that a given namespace can be used in multiple files.

Like Unix directories Perl namespaces are hierarchical and one namespace can be a part of another. The Unix filesystem's tremendous power and flexibility comes from the ability to put files in a multilevel directory tree and then locate them using the directory path. This makes it possible to access ten of thousands files belonging to operating system and various applications. Files with the same name but in different directories can coexist. For example:

/etc/hosts 
/etc/sysconfig/hosts
The same is true for Perl namespaces. Perl can stores functions and variables inside a complex hierarchy of namespaces too. The above herarchy would be represented in Perl as:
$etc::hosts
$stc::sysconfig::hosts

Like directory can store any type of file, namespaces can store any type of variables: scalar, arrays, hashes, functions, etc. The digram '::' serves as the separator between herarchically organized namespaces, just as '/' is the separator in the UNIX world. There are two basic ways to specify the namespace to which a variable belongs:

Like with directories the standard way of referring variables and functions to a particular namespace is to append the namespace to the beginning, using digraph :: as a delimiter, for example,
Global::execute();
refers to the function execute in the namespace Global.
$Mail::message;
refers to the scalar message in the namespace Mail
print keys(%my::important::addresses);
prints out the keys of the hash %addresses in the namespace my::important

You can use the variable "%namespace::" to get a list of all the symbols declared in a given namespace. For example:

foreach $key (keys %Time::) {
   print "\$$key => $Time::{$key}\n"
   print "\@$key => @$Time::{$key}\n";
   print "\%$key => @{[%$Time::{$key}\n"]}\n"; 
}

Assignment to a typeglob

Assignment to a typeglobis an aliasing operation; that is, *dick = *richard; causes variables, subroutines, formats, and file and directory handles accessible via the identifier richard to also be accessible via the symbol dick . If you want to alias only a particular variable or subroutine, assign a reference instead: *dick = \$richard;

making "constant" scalars

Another use of symbol tables is for making "constant" scalars: *PI = \3.14159265358979; Now you cannot alter $PI , which is probably a good thing, all in all. This isn't the same as a constant subroutine, which is optimized at compile time. A constant subroutine is one prototyped to take no arguments and to return a constant expression; see "Inlining Constant Functions"

The use constant pragma is a convenient shorthand:

use constant PI => 3.14159;

Other options to segregate code in independent semi-isolated parts

In addition to namespaces Perl provides three options for segregating code into independent semi-isolated parts:

If we want to get Perl to read that file and use it as part of our own program, we have three ways of doing this:

Use is now dominant form and all standard modules are included via the use statement.

Review of literature

Perl documentation has man page for package statement.

perlmod -- Perl modules (packages and symbol tables), perlmodlib describes Perl stndard module

In two recommended free books

Useful articles are:

Some useful documents and informative posts are available at the Web sites www.perl.com and PerlMonks



package NAMESPACE

Here's the entry for 'package' in the perlfunc manpage:

    package NAMESPACE
    
    Declares the compilation unit as being in the given 
    namespace. The scope of the package declaration is from the 
    declaration itself through the end of the enclosing block 
    (the same scope as the local() operator).  All further 
    unqualified dynamic identifiers will be in this namespace.  A 
    package statement affects only dynamic variables--including 
    those you've used local() on--but not lexical variables  
    created with my(). Typically it would be the first 
    declaration in a file to be included by the require or use 
    operator.  You can switch into a package in more than one 
    place; it influences merely which symbol table is used by the 
    compiler for the rest of that block.  You can refer to 
    variables and filehandles in other packages by prefixing the 
    identifier with the package name and a double colon:  
    $Package::Variable.  If the package name is null, the
    main package as assumed.  That is, $::sail is equivalent to
    $main::sail.

The perl namespaces extension is designed as replacement of the standard means of declaring and importing symbols, such as the pragma use strict 'vars' and Exporter interface for modules. It makes the symbol lookup rules more similar to those in C++ :

Syntax

The namespace extension is implemented as a special compilation mode. It can be enabled and disabled for each lexical scope, just like use strict. Each package activated during the namespace compilation mode (with the package statement) is treated later as using namespaces, even if other parts of it are compiled in the standard, non-namespace mode. Mixing of both modes in one package is not a very good practice, however, as it could lead to unexpected exceptions caused by undeclared variables.

use namespaces; no namespaces;

Enables or disables the namespaces mode. The setting lasts up to the end of the current lexical scope. Note that the compilation of each source file starts with disabled namespace mode, even if the require or use statement which caused its inclusion lies in the namespace-enabled scope.

Enabling the namespace mode automatically implies no strict 'vars' and vice versa.
use namespaces 'AA', 'BB::CC', ...; 
Enables the namespace mode and sets the import list for all packages defined later in the current lexical scope. This is the analogon of the C++ directive using namespace ... .

The importing relation between packages is transitive. For example, the lookup list for the packages compiled after the statement shown above will consist of AA, the packages imported by AA, BB::CC, the packages imported by BB::CC, BB, and the packages imported by BB. To avoid multiple searches, duplicates in the lookup list are removed immediately.

no namespaces 'AA', 'BB::CC', ...;

Removes the named packages from the current import list, but lets the namespace compilation mode active. Note that this change will affect only packages defined after this statement.

Effects at the run time

Each reference to a variable, both reading and writing, is first checked whether it refers to a declared or imported variable. If not, and the name is unqualified, then a declared variable with this name is looked up in all packages comprising the lookup list, as explained above. If found, the variable is imported into the current package. Otherwise an exception is raised. A qualified variable name is only checked to be pre-declared, if not, an exception is raised as well.

The lookup operation is performed once per variable and package; the declaration check is performed once per variable and each expression (script line) using it which was ever executed. This way the performance penalty is constant and comparable to that of the traditional import mechanism.

Unqualified subroutine calls are resolved in the same manner, but in the case of a failure no special exception is raised, since it will be done by the perl interpreter itself. Taking a subroutine reference \&abc involves the lookup too. There is also a special function namespaces::lookup_sub('package_name', 'sub_name') returning the code reference or undef if the lookup fails.

eval '...' statements, as well as regular expressions with deferred evaluation (like s///e operators or $(?{ }) expressions), re-establish the namespace environment for the duration of the expression compilation.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Nov 22, 2017] perl modules

Nov 17, 2017 | perlmonks.com

Discipulus (Monsignor) on Nov 16, 2017 at 09:04 UTC

Re: perl modules

Hello codestroman and welcome to the monastery and to the wonderful world of Perl!

First of all, please, add <c> code tags </c> around your code and output.

Then be sure to have read the standard documentation: perlmod and perlnewmod

Infact a basic Perl module define a package and use Exporter to export functions in the using Perl program.

In my homenode i've collected a lot of links on about module creation

L*

Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

thanos1983 (Priest) on Nov 16, 2017 at 09:17 UTC

Re: perl modules

Hello codestroman

Just to add a minor suggestion here, to the full cover reply of fellow monk Discipulus . It will assist you a lot also to read Simple Module Tutorial

Update: Direct answer to your question can be found here How to add a relative directory to @INC with multiple possible solutions. I would strongly recommend to go through all the articles that all monks proposed.

Hope this helps, BR.

Seeking for Perl wisdom...on the process of learning...not there...yet!

hippo (Abbot) on Nov 16, 2017 at 09:21 UTC

Re: perl modules (Can't locate in @INC)
PLEASE HELP!!

This is a monastery - a place of quite contemplation. The louder you shout the less wisdom shall you receive.

The error message Can't locate dog.pm in @INC is pretty explicit. Either your module file is not called dog.pm in which case, change it or else your file dog.pm is not in any of the directories listed in @INC in which case either move it to one of those directories or else change @INC with use lib .

I also see, despite the lack of formatting in your post that your module doesn't use any namespace. You should probably address that. Perhaps a solid read through Simple Module Tutorial would be a good idea?

Anonymous Monk on Nov 16, 2017 at 09:07 UTC

Re: perl modules

use an absolute pathname in use lib

Anonymous Monk on Nov 16, 2017 at 15:16 UTC

Re: perl modules

Welcome to the language ... and, to the Monastery. The "simple module tutorial" listed above is a very good place to start. Like all languages of its kind, Perl looks at runtime for external modules in a prescribed list of places, in a specified order. You can affect this in several ways, as the tutorials describe. Please read them carefully.

In the Perl(-5) language, this list is stored in a pre-defined array variable called @INC and it is populated from a variety of sources: a base-list that is compiled directly into the Perl interpreter, the PERL5LIB environment-variable, use lib statements, and even direct modification of the variable itself. Perl searches this list from beginning to end and processes (only) the first matching file that it finds.

(Note that, in Perl, the use statement is actually a pragma, or declaration to the compiler, and as such it has many "uses" and a somewhat complicated syntax.)

Corion (Pope) on Nov 16, 2017 at 15:23 UTC

Re^2: perl modules


by Corion (Pope) on Nov 16, 2017 at 15:23 UTC

(Note that, in Perl, the use statement is actually a pragma, or declaration to the compiler, and as such it has many "uses" and a somewhat complicated syntax.)

Please no.

The word "pragma" has a special meaning in Perl, and it is highly confusing to claim that a Perl "keyword" would be a "pragma". use certainly is a keyword and nothing else.

If you mean to say something different, please describe in more words what you want to say.

[Nov 17, 2017] perl modules

Nov 17, 2017 | perlmonks.com

Discipulus (Monsignor) on Nov 16, 2017 at 09:04 UTC

Re: perl modules

Hello codestroman and welcome to the monastery and to the wonderful world of Perl!

First of all, please, add <c> code tags </c> around your code and output.

Then be sure to have read the standard documentation: perlmod and perlnewmod

Infact a basic perl module define a package and use Exporter to export functions in the using perl program.

In my homenode i've collected a lot of links on about module creation

L*


Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

thanos1983 (Priest) on Nov 16, 2017 at 09:17 UTC

Re: perl modules

Hello codestroman

Just to add a minor suggestion here, to the full cover reply of fellow monk Discipulus . It will assist you a lot also to read Simple Module Tutorial

Update: Direct answer to your question can be found here How to add a relative directory to @INC with multiple possible solutions. I would strongly recommend to go through all the articles that all monks proposed.

Hope this helps, BR.

Seeking for Perl wisdom...on the process of learning...not there...yet!

hippo (Abbot) on Nov 16, 2017 at 09:21 UTC

Re: perl modules (Can't locate in @INC)
PLEASE HELP!!

This is a monastery - a place of quite contemplation. The louder you shout the less wisdom shall you receive.

The error message Can't locate dog.pm in @INC is pretty explicit. Either your module file is not called dog.pm in which case, change it or else your file dog.pm is not in any of the directories listed in @INC in which case either move it to one of those directories or else change @INC with use lib .

I also see, despite the lack of formatting in your post that your module doesn't use any namespace. You should probably address that. Perhaps a solid read through Simple Module Tutorial would be a good idea?

Anonymous Monk on Nov 16, 2017 at 09:07 UTC

Re: perl modules

use an absolute pathname in use lib

Anonymous Monk on Nov 16, 2017 at 15:16 UTC

Re: perl modules

Welcome to the language ... and, to the Monastery. The "simple module tutorial" listed above is a very good place to start. Like all languages of its kind, Perl looks at runtime for external modules in a prescribed list of places, in a specified order. You can affect this in several ways, as the tutorials describe. Please read them carefully.

In the Perl(-5) language, this list is stored in a pre-defined array variable called @INC and it is populated from a variety of sources: a base-list that is compiled directly into the Perl interpreter, the PERL5LIB environment-variable, use lib statements, and even direct modification of the variable itself. Perl searches this list from beginning to end and processes (only) the first matching file that it finds.

(Note that, in Perl, the use statement is actually a pragma, or declaration to the compiler, and as such it has many "uses" and a somewhat complicated syntax.)

Corion (Pope) on Nov 16, 2017 at 15:23 UTC

Re^2: perl modules


by Corion (Pope) on Nov 16, 2017 at 15:23 UTC

(Note that, in Perl, the use statement is actually a pragma, or declaration to the compiler, and as such it has many "uses" and a somewhat complicated syntax.)

Please no.

The word "pragma" has a special meaning in Perl, and it is highly confusing to claim that a Perl "keyword" would be a "pragma". use certainly is a keyword and nothing else.

If you mean to say something different, please describe in more words what you want to say.

[Nov 16, 2017] Namespaces and modules

Nov 16, 2017 | perlmonks.com

on Feb 09, 2015 at 13:21 UTC ( # 1116049 = perlquestion : print w/replies , xml ) Need Help?? kzwix has asked for the wisdom of the Perl Monks concerning the following question:

Greetings, Ô wise monks !

I come to you because of a mystery I'd like to unravel: The module import code doesn't work as I expected. So, as I'm thinking that it probably is a problem with my chair-keyboard interface, rather than with the language, I need your help.

So, there are these modules I have, the first one goes like this:

use utf8; use Date::Manip; use LogsMarcoPolo; package LibOutils; BEGIN { require Exporter; # set the version for version checking our $VERSION = 1.00; # Inherit from Exporter to export functions and variables our @ISA = qw(Exporter); # Functions and variables which are exported by default our @EXPORT = qw(getDateDuJour getHeureActuelle getInfosSemaine ge tTailleRepertoire getInfosPartition getHashInfosContenuRepertoire dor mir); # Functions and variables which can be optionally exported our @EXPORT_OK = qw(); } # Under this line are definitions of local variables, and the subs. [download]

I also have another module, which goes like that:

use utf8; use strict; use warnings; use Cwd; # Module "CORE" use Encode; use LibOutils qw(getHeureActuelle); package LogsMarcoPolo; BEGIN { require Exporter; # set the version for version checking our $VERSION = 1.00; # Inherit from Exporter to export functions and variables our @ISA = qw(Exporter); # Functions and variables which are exported by default our @EXPORT = qw(setNomProgramme ouvreFichierPourLog assigneFluxPo urLog pushFlux popFlux init printAndLog); # Functions and variables which can be optionally exported our @EXPORT_OK = qw(); } # Here are other definitions of variables and subs, which I removed fo r the sake of clarity sub init { my ($nomDuProgramme, $pathLogGeneral, $pathLogErreurs) = @_; my $date = LibOutils::getDateDuJour(); # La date de l'appel à init() my $time = LibOutils::getHeureActuelle(); # L'heure de l'appel à init() $nomProgramme = $nomDuProgramme; # Ouverture du flux pour STDOUT: my $stdout = assigneFluxPourLog(*STDOUT); # On l'ajoute à la liste de flux 'OUT': pushFlux('OUT', $stdout); # Ouverture du flux pour STDERR: my $stderr = assigneFluxPourLog(*STDERR); # On l'ajoute à la liste de flux 'ERR', et à la liste 'DUO': pushFlux('ERR', $stderr); pushFlux('DUO', $stderr); if (defined $pathLogGeneral) { my $plg = $pathLogGeneral; $plg =~ s/<DATE>/$date/g; $plg =~ s/<TIME>/$time/g; my $logG = ouvreFichierPourLog($plg); pushFlux('OUT', $logG); pushFlux('DUO', $logG); } if (defined $pathLogErreurs) { my $ple = $pathLogErreurs; $ple =~ s/<DATE>/$date/g; $ple =~ s/<TIME>/$time/g; my $logE = ouvreFichierPourLog($ple); pushFlux('ERR', $logE); pushFlux('DUO', $logE); } } [download]

Now, look at the second module: When, in the "init" sub, I call the getDateDuJour() and getHeureActuelle() functions with an explicit namespace, it works fine.

If I remove the prefix, it doesn't work, even for the function whose name I put in the "qw(...)" chain after the use.

Would a fellow monk know why ?

choroba (Bishop) on Feb 09, 2015 at 13:24 UTC

Re: Namespaces and modules

By putting package after the use clauses, you are importing all the functions to the "main" namespace, not into your package's namespace. Moving the package declaration up should help. لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

kzwix (Sexton) on Feb 09, 2015 at 13:34 UTC

Re^2: Namespaces and modules


by kzwix (Sexton) on Feb 09, 2015 at 13:34 UTC

I wonder, could it have something to do with loop-including ?

I mean, package "LibOutils" uses "LogsMarcoPolo" (for its logging system), but "LogsMarcoPolo" uses "LibOutils" for its dates and times.

Could that circular include be the origin of this bug ?

Anonymous Monk on Feb 09, 2015 at 14:18 UTC

Re^3: Namespaces and modules
by Anonymous Monk on Feb 09, 2015 at 14:18 UTC
I wonder, could it have something to do with loop-including ?

Circular dependencies don't automatically cause a problem, it also depends on what the module does in its body (which you haven't shown). If you think there is a problem, a short piece of example code that reproduces the problem would help, see http://sscce.org/

But first, did you try what choroba suggested ?

kzwix (Sexton) on Feb 09, 2015 at 15:04 UTC

Re^4: Namespaces and modules
by kzwix (Sexton) on Feb 09, 2015 at 15:04 UTC

Corion (Pope) on Feb 09, 2015 at 15:11 UTC

Re^5: Namespaces and modules
by Corion (Pope) on Feb 09, 2015 at 15:11 UTC

Anonymous Monk on Feb 09, 2015 at 15:59 UTC

Re^5: Namespaces and modules
by Anonymous Monk on Feb 09, 2015 at 15:59 UTC

Anonymous Monk on Feb 09, 2015 at 14:11 UTC

Re: Namespaces and modules
doesn't work as I expected ... it works fine ... it doesn't work

What are the exact error messages? What is the expected behavior vs. the behavior you're getting? See How do I post a question effectively?

Replies are listed 'Best First'.

[Nov 14, 2017] scoping - What is the difference between my and local in Perl - Stack Overflow

Notable quotes:
"... temporarily changes the value of the variable ..."
"... within the scope ..."
"... Unlike dynamic variables created by the local operator, lexical variables declared with my are totally hidden from the outside world, including any called subroutines. ..."
Nov 14, 2017 | stackoverflow.com

down vote favorite 10

Brian G ,Sep 24, 2008 at 20:12

I am seeing both of them used in this script I am trying to debug and the literature is just not clear. Can someone demystify this for me?

J.J. ,Sep 24, 2008 at 20:24

Dynamic Scoping. It is a neat concept. Many people don't use it, or understand it.

Basically think of my as creating and anchoring a variable to one block of {}, A.K.A. scope.

my $foo if (true); # $foo lives and dies within the if statement.

So a my variable is what you are used to. whereas with dynamic scoping $var can be declared anywhere and used anywhere. So with local you basically suspend the use of that global variable, and use a "local value" to work with it. So local creates a temporary scope for a temporary variable.

$var = 4;
print $var, "\n";
&hello;
print $var, "\n";

# subroutines
sub hello {
     local $var = 10;
     print $var, "\n";
     &gogo; # calling subroutine gogo
     print $var, "\n";
}
sub gogo {
     $var ++;
}

This should print:

4
10
11
4

Brad Gilbert ,Sep 24, 2008 at 20:50

You didn't call the subroutines. – Brad Gilbert Sep 24 '08 at 20:50

brian d foy ,Sep 25, 2008 at 18:23

Don't conditionally declare lexical variables: it has undefined behavior. – brian d foy Sep 25 '08 at 18:23

Jeremy Bourque ,Sep 24, 2008 at 20:26

The short answer is that my marks a variable as private in a lexical scope, and local marks a variable as private in a dynamic scope.

It's easier to understand my , since that creates a local variable in the usual sense. There is a new variable created and it's accessible only within the enclosing lexical block, which is usually marked by curly braces. There are some exceptions to the curly-brace rule, such as:

foreach my $x (@foo) { print "$x\n"; }

But that's just Perl doing what you mean. Normally you have something like this:

sub Foo {
   my $x = shift;

   print "$x\n";
}

In that case, $x is private to the subroutine and it's scope is enclosed by the curly braces. The thing to note, and this is the contrast to local , is that the scope of a my variable is defined with respect to your code as it is written in the file. It's a compile-time phenomenon.

To understand local , you need to think in terms of the calling stack of your program as it is running. When a variable is local , it is redefined from the point at which the local statement executes for everything below that on the stack, until you return back up the stack to the caller of the block containing the local .

This can be confusing at first, so consider the following example.

sub foo { print "$x\n"; }
sub bar { local $x; $x = 2; foo(); }

$x = 1;
foo(); # prints '1'
bar(); # prints '2' because $x was localed in bar
foo(); # prints '1' again because local from foo is no longer in effect

When foo is called the first time, it sees the global value of $x which is 1. When bar is called and local $x runs, that redefines the global $x on the stack. Now when foo is called from bar , it sees the new value of 2 for $x . So far that isn't very special, because the same thing would have happened without the call to local . The magic is that when bar returns we exit the dynamic scope created by local $x and the previous global $x comes back into scope. So for the final call of foo , $x is 1.

You will almost always want to use my , since that gives you the local variable you're looking for. Once in a blue moon, local is really handy to do cool things.

Drew Stephens ,Sep 24, 2008 at 22:58

Quoting from Learning Perl :

But local is misnamed, or at least misleadingly named. Our friend Chip Salzenberg says that if he ever gets a chance to go back in a time machine to 1986 and give Larry one piece of advice, he'd tell Larry to call local by the name "save" instead.[14] That's because local actually will save the given global variable's value away, so it will later automatically be restored to the global variable. (That's right: these so-called "local" variables are actually globals!) This save-and-restore mechanism is the same one we've already seen twice now, in the control variable of a foreach loop, and in the @_ array of subroutine parameters.

So, local saves a global variable's current value and then set it to some form of empty value. You'll often see it used to slurp an entire file, rather than leading just a line:

my $file_content;
{
    local $/;
    open IN, "foo.txt";
    $file_content = <IN>;
}

Calling local $/ sets the input record separator (the value that Perl stops reading a "line" at) to an empty value, causing the spaceship operator to read the entire file, so it never hits the input record separator.

Aristotle Pagaltzis ,Sep 25, 2008 at 23:25

I can't believe no one has linked to Mark Jason Dominus' exhaustive treatises on the matter:

dan1111 ,Jan 28, 2013 at 11:21

Word of warning: both of these articles are quite old, and the second one (by the author's own warning) is obsolete. It demonstrates techniques for localization of file handles that have been superseded by lexical file handles in modern versions of Perl. – dan1111 Jan 28 '13 at 11:21

Floegipoky ,Jan 23, 2015 at 16:51

As in Clinton was President (of the US) when the first was written – Floegipoky Jan 23 '15 at 16:51

Steve Jessop ,Sep 24, 2008 at 20:21

http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()

Unlike dynamic variables created by the local operator, lexical variables declared with my are totally hidden from the outside world, including any called subroutines. This is true if it's the same subroutine called from itself or elsewhere--every call gets its own copy.

http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local()

A local modifies its listed variables to be "local" to the enclosing block, eval, or do FILE --and to any subroutine called from within that block. A local just gives temporary values to global (meaning package) variables. It does not create a local variable. This is known as dynamic scoping. Lexical scoping is done with my, which works more like C's auto declarations.

I don't think this is at all unclear, other than to say that by "local to the enclosing block", what it means is that the original value is restored when the block is exited.

dlamblin ,Sep 24, 2008 at 20:14

Well Google really works for you on this one: http://www.perlmonks.org/?node_id=94007

From the link:

Quick summary: 'my' creates a new variable, 'local' temporarily amends the value of a variable.

ie, 'local' temporarily changes the value of the variable , but only within the scope it exists in.

Generally use my, it's faster and doesn't do anything kind of weird.

Kevin Crumley ,Sep 24, 2008 at 20:27

While this may be true, it's basically a side effect of the fact that "local"s are intended to be visible down the callstack, while "my"s are not. And while overriding the value of a global may be the main reason for using "local", there's no reason you can't use "local" to define a new variable. – Kevin Crumley Sep 24 '08 at 20:27

1800 INFORMATION ,Jan 21, 2009 at 10:02

local does not actually define a new variable. For example, try using local to define a variable when option explicit is enabled. You need to use "our" or "my" to define a new global or local variable. "local" is correctly used to give a variable a new value – 1800 INFORMATION Jan 21 '09 at 10:02

1800 INFORMATION ,Jan 29, 2009 at 10:45

Jesus did I really say option explicit to refer to the Perl feature. I meant obviously "use strict". I've obviously not coded in Perl in a while – 1800 INFORMATION Jan 29 '09 at 10:45

catfood ,Sep 24, 2008 at 20:18

From man perlsub :

Unlike dynamic variables created by the local operator, lexical variables declared with my are totally hidden from the outside world, including any called subroutines.

So, oversimplifying, my makes your variable visible only where it's declared. local makes it visible down the call stack too. You will usually want to use my instead of local .

Michael Carman ,Sep 25, 2008 at 2:00

Your confusion is understandable. Lexical scoping is fairly easy to understand but dynamic scoping is an unusual concept. The situation is made worse by the names my and local being somewhat inaccurate (or at least unintuitive) for historical reasons.

my declares a lexical variable -- one that is visible from the point of declaration until the end of the enclosing block (or file). It is completely independent from any other variables with the same name in the rest of the program. It is private to that block.

local , on the other hand, declares a temporary change to the value of a global variable. The change ends at the end of the enclosing scope, but the variable -- being global -- is visible anywhere in the program.

As a rule of thumb, use my to declare your own variables and local to control the impact of changes to Perl's built-in variables.

For a more thorough description see Mark Jason Dominus' article Coping with Scoping .

skiphoppy ,Sep 25, 2008 at 18:52

local is an older method of localization, from the times when Perl had only dynamic scoping. Lexical scoping is much more natural for the programmer and much safer in many situations. my variables belong to the scope (block, package, or file) in which they are declared.

local variables instead actually belong to a global namespace. If you refer to a variable $x with local, you are actually referring to $main::x, which is a global variable. Contrary to what it's name implies, all local does is push a new value onto a stack of values for $main::x until the end of this block, at which time the old value will be restored. That's a useful feature in and of itself, but it's not a good way to have local variables for a host of reasons (think what happens when you have threads! and think what happens when you call a routine that genuinely wants to use a global that you have localized!). However, it was the only way to have variables that looked like local variables back in the bad old days before Perl 5. We're still stuck with it.

andy ,Sep 24, 2008 at 20:18

"my" variables are visible in the current code block only. "local" variables are also visible where ever they were visible before. For example, if you say "my $x;" and call a sub-function, it cannot see that variable $x. But if you say "local $/;" (to null out the value of the record separator) then you change the way reading from files works in any functions you call.

In practice, you almost always want "my", not "local".

Abhishek Kulkarni ,Apr 10, 2013 at 5:44

Look at the following code and its output to understand the difference.
our $name = "Abhishek";

sub sub1
{
    print "\nName = $name\n";
    local $name = "Abhijeet";

    &sub2;
    &sub3;
}

sub sub2
{
    print "\nName = $name\n";
}

sub sub3
{
    my $name = "Abhinav";
    print "\nName = $name\n";
}


&sub1;

Output is :

Name = Abhishek

Name = Abhijeet

Name = Abhinav

phreakre ,Oct 1, 2008 at 16:01

dinomite's example of using local to redefine the record delimiter is the only time I have ran across in a lot of perl programming. I live in a niche perl environment [security programming], but it really is a rarely used scope in my experience.

Saravanarajan

add a comment,Aug 6, 2009 at 8:12
&s;

sub s()
{
    local $s="5";
    &b;
    print $s;
}

sub b()
{
    $s++;
}

The above script prints 6.

But if we change local to my it will print 5.

This is the difference. Simple.

,

I think the easiest way to remember it is this way. MY creates a new variable. LOCAL temporarily changes the value of an existing variable.

[Nov 13, 2017] 'our' is not 'my' by Ovid

Notable quotes:
"... I didn't convert them to my variables because these variables were being declared in another package. ..."
"... the use of the variable name ..."
Nov 13, 2017 | perlmonks.com

Aug 16, 2001

Update: At the request of a couple of people, some as replies to this node and one as a private message, I have added a link to this node from the Tutorials section. I have linked it rather than repost it to tutorials as there is no reason for me to get the rep twice. I might add that I would not have done this were it not for the high rep this node has received (thus suggesting to me that monks find this information useful).

Many people misunderstand how our is used and I've often seen code where it's used as a synonym for my . This is not the case and I hope this clears up some of the differences. I'm posting this because I've run across this a few times lately and I thought I should just 'get it out there' for others.

There are basically two ways of declaring variables in Perl: global and lexical. A global variable has a package name prepending to it:

$main::foo; $CGI::POST_MAX; @foo::bar; [download]

All packages can access the variable $foo in the main symbol table ( %main:: or the shorthand %:: ) by using $main::foo . Global variables are generally a bad idea, but do crop up in a lot of code.

A lexically scoped variable is declared with my : my $foo; my $POST_MAX; my @bar; [download]

Though they look similar to the package variables above, they are not the same and cannot be accessed outside of the scope in which they were declared.

If you use strict and you try to access a variable that's not previously declared, you'll get an error similar to the following:

Global symbol "$foo" requires explicit package name at C:\test.pl line 2. [download]

Basically, Perl expects that you are trying to use a package variable, but left off the package name. The problem with using package names ( $main::foo ) is that strict ignores these variables and if you type $main::field in one place and $main::feild in another place, strict won't warn you of the typo.

our tries to help out by letting you use package variables without adding the package name. The following two variables are the same:

package foo; use strict; our $bar; # These are the same $foo::bar; # These are the same [download]

That eliminates the $main::f(ie|ei)ld problem by allowing you to do this:

our $field; [download]

From there, you just drop package names and the script will run and later Perl will kill the script if you try use $feild . Unfortunately, there are a lot of problems with this.

The main problem is that you are now using global variables which is generally a Bad Thing. Any code, anywhere, can change your global. Large systems with lots of globals typically suffer this problems and quickly become unmaintainable.

This also leads to very subtle coding errors. Try the following code:

use strict; for ( 1 .. 3 ) { &doit } sub doit { our $foo; print ++$foo . "\n"; } [download]

That will print 1, 2, and 3 on successive lines. Change the our to a my and it prints 1, 1, and 1. Because the my variable goes out of scope at the end of the sub and the our variable doesn't (since it's global), you get wildly different results.

There is one use I have found for our variables. if I am forced to maintain a large code base with lots of global variables, I usually expect to see lots of code problems, including misspellings of those globals that are overlooked due to the hacked nature of those code. For example, one site I worked on had some object-oriented code that stuffs a lot of data into package main (you can keep reading after you stop laughing). I've seen code like this:

$main::sql = $order->lineItemSQL; $main::dbh->prepare( $main::sql ); [download]

I know, it doesn't make a lot of sense (why doesn't it just return the line items instead of the SQL?), but I needed to clean up stuff like that. So, in my code, I put the following:

our ( $sql, $dbh ); #later $sql = $order->lineItemSQL; $dbh->prepare( $sql ); [download]

I didn't convert them to my variables because these variables were being declared in another package.

This doesn't seem like much benefit aside from eliminating a few bytes (and it certainly wasn't the best solution, but we've all had time constraints...). However, there is a huge benefit. Later in the code, when we encounter $main::slq , it becomes $slq and the program dies a much needed death.

As a side note: the primary difference (that I can see) between our and use vars appears to be that our lexically scopes the use of the variable name (not the variable) and the other does not. The following code snippets should clarify that:

use strict; { use vars qw/ $foo /; $foo = "Ovid"; } print $foo; [download]

That code will work fine. However, change the use vars qw/ $foo /; to our $foo and Perl dies, telling you that $foo requires an explicit package name. However, change the print statement to include the package name and all is well:

use strict; { our $foo; $foo = "Ovid"; } print $main::foo; [download]

This behavior may not seem immediately useful, but you can then use an our declaration at the top of a subroutine, strip off the package names in the sub, and not worry about this conflicting with my variables in the rest of the code.

use strict; my $foo = 'bar'; &baz; sub baz { our $foo = 7; print $foo; } print $foo; [download]

Change that code to use " use vars " and you'll see it print 7 twice, stepping on your my variable.

Interesting to note that the only uses I've found for our have been hacking bad code...

Cheers,
Ovid

Vote for paco !

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

dragonchild (Archbishop) on Aug 16, 2001 at 23:35 UTC

Re: 'our' is not 'my'

Good points, Ovid . ++! Personally, the only time I use our is in the following:

use 5.6.0; use strict; use warnings; package Foo; use Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(bar baz); # Code down here, including bar() and baz() [download] That way, I get to have the warmfuzzy feeling that I'm not using ickypoo globals, but, instead, using package-scoped globals. @ISA needing to be a global is why I even bother with our .

------
/me wants to be the brightest bulb in the chandelier!

Vote paco for President!

damian1301 (Curate) on Aug 17, 2001 at 03:21 UTC

Re: 'our' is not 'my'

I often see this error when people use the GetOpt modules. Good job Ovid, ++ (maybe could be a tutorial?).

$_.=($=+(6<<1));print(chr(my$a=$_));$^H=$_+$_;$_=$^H; print chr($_-39); # Easy but its ok. [download]

LD2 (Curate) on Aug 17, 2001 at 03:47 UTC

Re: Re: 'our' is not 'my'


by LD2 (Curate) on Aug 17, 2001 at 03:47 UTC

I second the suggestion, I think it'd be perfect for the tutorial section! Ovid ++!

ikegami (Pope) on Oct 26, 2007 at 12:02 UTC

Re: 'our' is not 'my'

There is a catch with our that doesn't exist with use vars :

package AA; $AA::var = __PACKAGE__; our $var; print "$var\n"; package BB; $BB::var = __PACKAGE__; print "$var\n"; # Prints 'AA'. [download]

Using curlies when using multiple packages in one file avoids the problem.

{ package AA; $AA::var = __PACKAGE__; our $var; print "$var\n"; } { package BB; $BB::var = __PACKAGE__; print "$var\n"; # Compile error! } [download]

Keeping that exception in mind, our is like no strict 'vars'; on a per-var basis.

ruzam (Curate) on Oct 26, 2007 at 15:45 UTC

Re^2: 'our' is not 'my'


by ruzam (Curate) on Oct 26, 2007 at 15:45 UTC

In your first example, how is it that 'our $var;' in package AA makes $var available to both package BB and package main? Why does package BB fall back to AA's result without any kind of warning?

ikegami (Pope) on Oct 26, 2007 at 16:09 UTC

Re^3: 'our' is not 'my'
by ikegami (Pope) on Oct 26, 2007 at 16:09 UTC

I prefer to think of our as the equivalent of no strict 'vars' for a single variable, but in reality, our creates a lexically-scoped variable aliased to a package variable.

In effect,
our $var;
is the same as
use Data::Alias;
alias my $var = $__PACKAGE__::var;
(Syntax issues aside.)

Unlike blocks and files, packages aren't lexical scopes. Switching package neither destroys the our variable (because the our variable is lexically scoped) nor change to which package variable the our variable is aliased (because package doesn't know anything about the our variable).

ruzam (Curate) on Oct 26, 2007 at 16:37 UTC

Re^4: 'our' is not 'my'
by ruzam (Curate) on Oct 26, 2007 at 16:37 UTC

JadeNB (Chaplain) on Nov 26, 2008 at 15:30 UTC

Re^5: 'our' is not 'my'
by JadeNB (Chaplain) on Nov 26, 2008 at 15:30 UTC

Tabari (Monk) on Oct 26, 2007 at 11:55 UTC

Re: 'our' is not 'my'

I was cleaning up some old code which did not use strict.
As it used a lot of global vars, I was forced to use our , the way you explained. I didn't know the exact meaning before
Tabari

Anonymous Monk on Nov 20, 2008 at 19:47 UTC

Re: 'our' is not 'my'

Is slq a typo?
This line:

However, there is a huge benefit. Later in the code, when we encounter $main::slq , it becomes $slq and the program dies a much needed death.

Did you mean sql ?

-J_Tom_Moon_79

StommePoes (Scribe) on Nov 26, 2008 at 09:55 UTC

Re^2: 'our' is not 'my'


by StommePoes (Scribe) on Nov 26, 2008 at 09:55 UTC

As I understand it, it's a deliberate typo to show that when using our , the typo called "slq" will get caught (instead of being treated like some new variable as happens when variables are global).

So, maybe I'm misunderstanding (I don't write speak or read Perl yet, lawlz), but I thought "slq" was the whole point.

Replies are listed 'Best First'.

[Nov 13, 2017] How to export names from one namespace into another

Nov 13, 2017 | stackoverflow.com

Rancho ,Apr 3, 2014 at 17:13

I have a variable $x which currently has a local scope in A.pm and I want to use the output of $x (which is usually PASSED/FAILED) in an if else statement in B.pm

Something like below

A.pm:

if (condition1) { $x = 'PASSED'; }
if (condition2) { $x = 'FAILED'; }

B.pm:

if ($x=='PASSED') { $y=1; } else { $y=0; }

I tried using require ("A.pm"); in B.pm but it gives me an error global symbol requires an explicit package name which means it is not able to read the variable from require. Any inputs would help

Borodin ,Apr 3, 2014 at 17:27

This sounds like a very strange configuration. Your A.pm has executable code as well as values that you want to access externally. Is that code in subroutines? Are you aware that any code outside a subroutine will be executed the first time the external code requires the file? You need to show us the contents of A.pm or we can't help you much. – Borodin Apr 3 '14 at 17:27

Jonathan Leffler ,Apr 3, 2014 at 17:29

Normally, you'd return $x from a function defined in A and called in B; this is a much cleaner, less pathological way of getting at the information. – Jonathan Leffler Apr 3 '14 at 17:29

Rancho ,Apr 3, 2014 at 17:41

Yes the above if conditions in A.pm are in a subroutine. Is there a way I could read that subroutine outside to extract the value of $x? – Rancho Apr 3 '14 at 17:41

ysth ,Apr 3, 2014 at 18:04

there is a core module named B - avoid using that name even in examples. – ysth Apr 3 '14 at 18:04

David W. ,Apr 3, 2014 at 19:08

I have a variable $x which currently has a local scope in A.pm and I want to use the output of $x (which is usually PASSED/FAILED) in an if else statement in B.pm

We could show you how to do this, but this is a really bad, awful idea.

There's a reason why variables are scoped, and even global variables declared with our and not my are still scoped to a particular package.

Imagine someone modifying one of your packages, and not realizing there's a direct connection to a variable name $x . They could end up making a big mess without even knowing why.

What I would HIGHLY recommend is that you use functions (subroutines) to pass around the value you need:

Local/A.pm
package Local::A;
use strict;
use warnings;
use lib qw($ENV{HOME});


use Exporter qw(import);
our @EXPORT_OK = qw(set_condition);

sub set_condition {
    if ( condition1 ) {
       return "PASSED";
    elsif ( condition2 ) {
       return "FALSED";
    else {
       return "Huh?";
}
1;

Here's what I did:

Local/B.pm
package Local::B;
use lib qw($ENV{HOME});

use Local::A qw(set_condition);

my $condition = set_contition();

my $y;
if ( $condition eq 'PASSED' ) {   # Note: Use `eq` and not `==` because THIS IS A STRING!
   $y = 1;
else {
   $y = 0;
}
1;

If all of this looks like mysterious magic, you need to read about Perl modules . This isn't light summer reading. It can be a bit impenetrable, but it's definitely worth the struggle. Or, get Learning Perl and read up on Chapter 11.

Rancho ,Apr 23, 2014 at 16:57

Thanks a lot for the detailed explanation. Appreciate it – Rancho Apr 23 '14 at 16:57

Miller ,Apr 3, 2014 at 17:21

After you require A; , you can then access the variable by giving it an explicit package name like the error message says.

in B.pm:

my $y = $A::x eq 'PASSED ? 1 : 0

The variable $x will have to be declared with our instead of my .

Finally, use eq instead of == for doing string comparisons.

Borodin ,Apr 3, 2014 at 17:24

... as long as $x isn't a lexical variable declared with myBorodin Apr 3 '14 at 17:24

[Nov 13, 2017] aristotle73

Nov 13, 2017 | perlmonks.com

Variable Scoping in Perl: the basics

print "$Robert has canned $name's sorry butt\n"; I tried running this in PERL and it yelled at me saying that it didn't like $name::s. I changed this line of code to: print "$Robert has canned $name sorry butt\n"; And it worked fine 0_o An error in the tutorial perhaps?

Aristotle (Chancellor) on Dec 24, 2004 at 01:50 UTC

Re^2: Variable Scoping in Perl: the basics


by Aristotle (Chancellor) on Dec 24, 2004 at 01:50 UTC

Try

print "$Robert has canned ${name}'s sorry butt\n"; [download]

The apostrophe is the old-style package separator, still supported, so $name's is indeed equivalent to $name::s . By putting the curlies in there, you tell Perl exactly which part of the string to consider part of the variable name, and which part to consider a literal value.

[Nov 13, 2017] Variable Scope

Nov 13, 2017 | perlmonks.com

on Nov 10, 2017 at 16:52 UTC ( # 1203128 = perlquestion : print w/replies , xml ) Need Help?? dave741 has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/local/bin/perl use strict; foreach my $name ('A', 'B') { my $res = 'Init' if (0); if (defined ($res)) { print "$name: res = $res\n"; } else { print "$name: res is undef\n" } $res = 'Post'; } [download]
Result:
A: res is undef
B: res = Post

As $res is under lexical variable scope, shouldn't it disappear at the bottom of the block
and be recreated by the second pass, producing an identical result?
Bug? Feature? Saving CPU?

perl -v
This is perl, v5.10.1 (*) built for x86_64-linux-thread-multi

Thoughts?
Dave

haukex (Monsignor) on Nov 10, 2017 at 16:55 UTC

Re: Variable Scope (updated)

From perlsyn :

NOTE: The behaviour of a my , state , or our modified with a statement modifier conditional or loop construct (for example, my $x if ... ) is undefined . The value of the my variable may be undef , any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

Update: Heh, Eily and I posted within 4 seconds of another ;-)

Update 2: Historically, sometimes this "feature/bug" was (ab)used to make variables " static ", just two references of many found with a quick search: Unusual Closure Behaviour , Re: Making a variable in a sub retain its value between calls . The better ways to do this are described in Persistent Private Variables :

BEGIN { my $static_val = 0; sub gimme_another { return ++$static_val; } } # - OR - in Perl >=5.10: use feature 'state'; sub gimme_another { state $static_val = 0; return ++$static_val; } [download]

But nowadays, anywhere you see the pattern, it should be considered a bug, see "Using my() in false conditional" in perldeprecation . On Perl 5.26:

$ perl -e 'my $x if 0' Deprecated use of my() in false conditional. This will be a fatal erro r in Perl 5.30 at -e line 1. [download]

Update 3: Apparently, the warning " Deprecated use of my() in false conditional " first showed up in Perl 5.10 and became a default warning in 5.12. Note that your Perl 5.10.1 is now more than eight years old, and you should upgrade. Also, you should generally use warnings; ( Use strict and warnings ).

Eily (Parson) on Nov 10, 2017 at 16:55 UTC

Re: Variable Scope

According to perlsyn :

NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ... ) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.
So neither bug nor feature, third option.

AnomalousMonk (Chancellor) on Nov 10, 2017 at 17:07 UTC

Re: Variable Scope

See the state feature from Perl 5.10 onward for similar "static variable" behavior that is well-defined.


Give a man a fish : <%-{-{-{-<

Replies are listed 'Best First'.

[Nov 13, 2017] How to declare perl variable without using my - Stack Overflow

Nov 13, 2017 | stackoverflow.com

down vote favorite 1

DavidO ,May 22, 2013 at 2:04

I'm new to Perl programming. I've noticed that every time I want to declare a new variable, I should use the my keyword before that variable if strict and warnings are on (which I was told to do, for reasons also I do not know.)

So how to declare a variable in perl without using my and without getting warnings?

My question is: Is it possible to declare a variable without using my and without omitting the use strict; and use warnings; and without getting warnings at all?

[Nov 06, 2017] scope - What is the difference between my and our in Perl - Stack Overflow

Notable quotes:
"... use strict "vars" ..."
Nov 06, 2017 | stackoverflow.com

Fran Corpier , May 20, 2009 at 2:22

Great question: How does our differ from my and what does our do?

In Summary:

Available since Perl 5, my is a way to declare:

On the other hand, our variables are:

Declaring a variable with our allows you to predeclare variables in order to use them under use strict without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars , which was only file-scoped, and not lexically scoped as is our

For example, the formal, qualified name for variable $x inside package main is $main::x . Declaring our $x allows you to use the bare $x variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict or use strict "vars" . The scope might be one, or two, or more packages, or one small block.

Nathan Fellman , Aug 23, 2009 at 13:51

So how does our differ from local? – Nathan Fellman Aug 23 '09 at 13:51

ikegami , Sep 21, 2011 at 16:57

@Nathan Fellman, local doesn't create variables. It doesn't relate to my and our at all. local temporarily backs up the value of variable and clears its current value. – ikegami Sep 21 '11 at 16:57

ikegami , Nov 20, 2016 at 1:15

our variables are not package variables. They aren't globally-scoped, but lexically-scoped variables just like my variables. You can see that in the following program: package Foo; our $x = 123; package Bar; say $x; . If you want to "declare" a package variable, you need to use use vars qw( $x ); . our $x; declares a lexically-scoped variable that is aliased to the same-named variable in the package in which the our was compiled. – ikegami Nov 20 '16 at 1:15

bubaker , May 10, 2009 at 14:00

The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:

my variables are lexically scoped within a single block defined by {} or within the same file if not in {} s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.

our variables are scoped within a package/file and accessible from any code that use or require that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.

Just to round it out, local variables are "dynamically" scoped, differing from my variables in that they are also accessible from subroutines called within the same block.

Georg , Oct 1, 2016 at 6:41

+1 for " my variables are lexically scoped [...] within the same file if not in {} s". That was useful for me, thanks. – Georg Oct 1 '16 at 6:41

FMc , Jun 13, 2009 at 16:11

An example:
use strict;

for (1 .. 2){
    # Both variables are lexically scoped to the block.
    our ($o);  # Belongs to 'main' package.
    my  ($m);  # Does not belong to a package.

    # The variables differ with respect to newness.
    $o ++;
    $m ++;
    print __PACKAGE__, " >> o=$o m=$m\n";  # $m is always 1.

    # The package has changed, but we still have direct,
    # unqualified access to both variables, because the
    # lexical scope has not changed.
    package Fubb;
    print __PACKAGE__, " >> o=$o m=$m\n";
}

# The our() and my() variables differ with respect to privacy.
# We can still access the variable declared with our(), provided
# that we fully qualify its name, but the variable declared
# with my() is unavailable.
print __PACKAGE__, " >> main::o=$main::o\n";  # 2
print __PACKAGE__, " >> main::m=$main::m\n";  # Undefined.

# Attempts to access the variables directly won't compile.
# print __PACKAGE__, " >> o=$o\n";
# print __PACKAGE__, " >> m=$m\n";

# Variables declared with use vars() are like those declared
# with our(): belong to a package; not private; and not new.
# However, their scoping is package-based rather than lexical.
for (1 .. 9){
    use vars qw($uv);
    $uv ++;
}

# Even though we are outside the lexical scope where the
# use vars() variable was declared, we have direct access
# because the package has not changed.
print __PACKAGE__, " >> uv=$uv\n";

# And we can access it from another package.
package Bubb;
print __PACKAGE__, " >> main::uv=$main::uv\n";

Nathan Fellman , Jun 13, 2009 at 17:52

Good answer. It's a shame I can't upvote it more than once – Nathan Fellman Jun 13 '09 at 17:52

Roland Illig , Nov 20, 2015 at 18:46

Instead of # 5 , the comment should read # 2 . – Roland Illig Nov 20 '15 at 18:46

daotoad , May 10, 2009 at 16:37

Coping with Scoping is a good overview of Perl scoping rules. It's old enough that our is not discussed in the body of the text. It is addressed in the Notes section at the end.

The article talks about package variables and dynamic scope and how that differs from lexical variables and lexical scope.

ismail , May 10, 2009 at 10:27

my is used for local variables, where as our is used for global variables. More reading over Variable Scoping in Perl: the basics .

Chas. Owens , May 11, 2009 at 0:16

Be careful tossing around the words local and global. The proper terms are lexical and package. You can't create true global variables in Perl, but some already exist like $_, and local refers to package variables with localized values (created by local), not to lexical variables (created with my). – Chas. Owens May 11 '09 at 0:16

MJD , Oct 7, 2013 at 14:02

${^Potato} is global. It refers to the same variable regardless of where you use it. – MJD Oct 7 '13 at 14:02

Xu Ding , Nov 7, 2013 at 15:31

It's an old question, but I ever met some pitfalls about lexical declarations in Perl that messed me up, which are also related to this question, so I just add my summary here:

1. definition or declaration?

local $var = 42; 
print "var: $var\n";

The output is var: 42 . However we couldn't tell if local $var = 42; is a definition or declaration. But how about this:

use strict;
use warnings;

local $var = 42;
print "var: $var\n";

The second program will throw an error:

Global symbol "$var" requires explicit package name.

$var is not defined, which means local $var; is just a declaration! Before using local to declare a variable, make sure that it is defined as a global variable previously.

But why this won't fail?

use strict;
use warnings;

local $a = 42;
print "var: $a\n";

The output is: var: 42 .

That's because $a , as well as $b , is a global variable pre-defined in Perl. Remember the sort function?

2. lexical or global?

I was a C programmer before starting using Perl, so the concept of lexical and global variables seems straightforward to me: just corresponds to auto and external variables in C. But there're small differences:

In C, an external variable is a variable defined outside any function block. On the other hand, an automatic variable is a variable defined inside a function block. Like this:

int global;

int main(void) {
    int local;
}

While in Perl, things are subtle:

sub main {
    $var = 42;
}

&main;

print "var: $var\n";

The output is var: 42 , $var is a global variable even it's defined in a function block! Actually in Perl, any variable is declared as global by default.

The lesson is to always add use strict; use warnings; at the beginning of a Perl program, which will force the programmer to declare the lexical variable explicitly, so that we don't get messed up by some mistakes taken for granted.

ruffin , Feb 10, 2015 at 19:47

More on ["remembering [$a and $b in] sort" here]( stackoverflow.com/a/26128328/1028230 ). Perl never ceases to, um, astound me. – ruffin Feb 10 '15 at 19:47

Σlafur Waage , May 10, 2009 at 10:25

The perldoc has a good definition of our.

Unlike my, which both allocates storage for a variable and associates a simple name with that storage for use within the current scope, our associates a simple name with a package variable in the current package, for use within the current scope. In other words, our has the same scoping rules as my, but does not necessarily create a variable.

Misha Gale , Dec 2, 2011 at 15:03

This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.
#!/usr/bin/perl

our $foo = "BAR";

print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";

Output:

BAR
BAZ

This won't work if you change 'our' to 'my'.

Cosmicnet , Oct 21, 2014 at 14:08

Not so. $foo ${foo} ${'foo'} ${"foo"} all work the same for variable assignment or dereferencing. Swapping the our in the above example for my does work. What you probably experienced was trying to dereference $foo as a package variable, such as $main::foo or $::foo which will only work for package globals, such as those defined with our . – Cosmicnet Oct 21 '14 at 14:08

Misha Gale , Oct 21, 2014 at 17:50

Just retested using v5.20, and it definitely doesn't give the same output with my (it prints BAR twice.) – Misha Gale Oct 21 '14 at 17:50

Cosmicnet , Nov 22, 2014 at 13:44

My test (on windows): perl -e "my $foo = 'bar'; print $foo; ${foo} = 'baz'; pr int $foo" output: barbaz perl -e "my $foo = 'bar'; print $foo; ${"foo"} = 'baz'; print $foo" output: barbaz perl -e "my $foo = 'bar'; print $foo; ${\"foo\"} = 'baz'; print $foo" output: barbar So in my testing I'd fallen into the same trap. ${foo} is the same as $foo, the brackets are useful when interpolating. ${"foo"} is actually a look up to $main::{} which is the main symbol table, as such only contains package scoped variables. – Cosmicnet Nov 22 '14 at 13:44

Cosmicnet , Nov 22, 2014 at 13:57

${"main::foo"}, ${"::foo"}, and $main::foo are the same as ${"foo"}. The shorthand is package sensitive perl -e "package test; our $foo = 'bar'; print $foo; ${\"foo\"} = 'baz'; print $foo" works, as in this context ${"foo"} is now equal to ${"test::foo"}. Of Symbol Tables and Globs has some information on it, as does the Advanced Perl programming book. Sorry for my previous mistake. – Cosmicnet Nov 22 '14 at 13:57

Lavi Buchnik , Sep 5, 2014 at 12:09

print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";

package Changed;
{
        my $test = 10;
        my $test1 = 11;
        print "trying to print local vars from a closed block: $test, $test1\n";
}

&Check_global;

sub Check_global {
        print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package:     $test\n";
print "trying to print local var outside the block $test1\n";

Will Output this:

package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block

In case using "use strict" will get this failure while attempting to run the script:

Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.

Okuma.Scott , Sep 5, 2014 at 12:29

Please provide some kind of explanation. Dumping code like this is rarely considered appropriate. – Okuma.Scott Sep 5 '14 at 12:29

Lavi Buchnik , Sep 6, 2014 at 20:08

in simple words: Our (as the name sais) is a variable decliration to use that variable from any place in the script (function, block etc ...), every variable by default (in case not declared) belong to "main" package, our variable still can be used even after decliration of another package in the script. "my" variable in case declared in a block or function, can be used in that block/function only. in case "my" variable was declared not closed in a block, it can be used any where in the scriot, in a closed block as well or in a function as "our" variable, but can't used in case package changed – Lavi Buchnik Sep 6 '14 at 20:08

Lavi Buchnik , Sep 6, 2014 at 20:13

My script above shows that by default we are in the "main" package, then the script print an "our" variable from "main" package (not closed in a block), then we declare two "my" variables in a function and print them from that function. then we print an "our" variable from another function to show it can be used in a function. then we changing the package to "changed" (not "main" no more), and we print again the "our" variable successfully. then trying to print a "my" variable outside of the function and failed. the script just showing the difference between "our" and "my" usage. – Lavi Buchnik Sep 6 '14 at 20:13

Yugdev , Nov 5, 2015 at 11:08

Just try to use the following program :
#!/usr/local/bin/perl
use feature ':5.10';
#use warnings;
package a;
{
my $b = 100;
our $a = 10;


print "$a \n";
print "$b \n";
}

package b;

#my $b = 200;
#our $a = 20 ;

print "in package b value of  my b $a::b \n";
print "in package b value of our a  $a::a \n";

Nathan Fellman , Nov 5, 2015 at 13:11

yes, but why is that? – Nathan Fellman Nov 5 '15 at 13:11

Yugdev , Nov 5, 2015 at 14:03

This explains the difference between my and our. The my variable goes out of scope outside the curly braces and is garbage collected but the our variable still lives. – Yugdev Nov 5 '15 at 14:03

xoid , May 16, 2013 at 8:02

#!/usr/bin/perl -l

use strict;

# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'

our $lol = eval {$lol} || 'lol' ;

print $lol;

Nathan Fellman , May 16, 2013 at 11:07

Can you explain what this code is meant to demonstrate? Why are our and my different? How does this example show it? – Nathan Fellman May 16 '13 at 11:07

Evgeniy , Jan 27, 2016 at 4:57

Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.

On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.

The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.

Sources:

[Nov 06, 2017] How to create a Perl Module for code reuse

Nov 06, 2017 | perlmaven.com

You may be creating more and more scripts for your systems, which need to use the same functions.

You already mastered the ancient art of copy-paste, but you are not satisfied with the result.

You probably know lots of Perl modules that allow you to use their functions and you also want to create one.

However, you don't know how to create such a module.

The module

  1. package My :: Math
  2. use strict
  3. use warnings
  4. use Exporter qw import );
  5. our @EXPORT_OK = qw add multiply );
  6. sub add
  7. my $x $y = @_
  8. return $x $y
  9. sub multiply
  10. my $x $y = @_
  11. return $x $y

Save this in somedir/lib/My/Math.pm (or somedir\lib\My\Math.pm on Windows).

The script
  1. #!/usr/bin/perl
  2. use strict
  3. use warnings
  4. use My :: Math qw add );
  5. print add 19 23 );

Save this in somedir/bin/app.pl (or somedir\bin\app.pl on Windows).

Now run perl somedir/bin/app.pl . (or perl somedir\bin\app.pl on Windows).

It is going to print an error like this:

Can't locate My/Math.pm in @INC (@INC contains:
...
...
...
BEGIN failed--compilation aborted at somedir/bin/app.pl line 9.
What is the problem?

In the script we loaded the module with the use keyword. Specifically with the use My::Math qw(add); line. This searches the directories listed in the built-in @INC variable looking for a subdirectory called My and in that subdirectory for a file called Math.pm .

The problem is that your .pm file is not in any of the standard directories of perl: it is not in any of the directories listed in @INC.

You could either move your module, or you could change @INC.

The former can be problematic, especially on systems where there is a strong separation between the system administrator and the user. For example on Unix and Linux system only the user "root" (the administrator) has write access to these directories. So in general it is easier and more correct to change @INC.

Change @INC from the command line

Before we try to load the module, we have to make sure the directory of the module is in the @INC array.

Try this:

perl -Isomedir/lib/ somedir/bin/app.pl .

This will print the answer: 42.

In this case, the -I flag of perl helped us add a directory path to @INC.

Change @INC from inside the script

Because we know that the "My" directory that holds our module is in a fixed place relative to the script, we have another possibility for changing the script:

  1. #!/usr/bin/perl
  2. use strict
  3. use warnings
  4. use File :: Basename qw dirname );
  5. use Cwd qw abs_path );
  6. use lib dirname dirname abs_path $0 '/lib'
  7. use My :: Math qw add );
  8. print add 19 23 );

and run it again with this command:

perl somedir/bin/app.pl .

Now it works.

Let's explain the change:

How to change @INC to point to a relative directory

This line: use lib dirname(dirname abs_path $0) . '/lib'; adds the relative lib directory to the beginning of @INC

$0 holds the name of the current script. abs_path() of Cwd returns the absolute path to the script.

Given a path to a file or to a directory the call to dirname() of File::Basename returns the directory part, except of the last part.

In our case $0 contains app.pl

abs_path($0) returns .../somedir/bin/app.pl

dirname(abs_path $0) returns .../somedir/bin

dirname( dirname abs_path $0) returns .../somedir

That's the root directory of our project.

dirname( dirname abs_path $0) . '/lib' then points to .../somedir/lib

So what we have there is basically

use lib '.../somedir/lib';

but without hard-coding the actual location of the whole tree.

The whole task of this call is to add the '.../somedir/lib' to be the first element of @INC.

Once that's done, the subsequent call to use My::Math qw(add); will find the 'My' directory in '.../somedir/lib' and the Math.pm in '.../somedir/lib/My'.

The advantage of this solution is that the user of the script does not have to remember to put the -I... on the command line.

There are other ways to change @INC for you use in other situations.

Explaining use

So as I wrote earlier, the use call will look for the My directory and the Math.pm file in it.

The first one it finds will be loaded into memory and the import function of My::Math will be called with the parameters after the name of the module. In our case import( qw(add) ) which is just the same as calling import( 'add' )

The explanation of the script

There is not much left to explain in the script. After the use statement is done calling the import function, we can just call the newly imported add function of the My::Math module. Just as if I declared the function in the same script.

What is more interesting is to see the parts of the module.

The explanation of the module

A module in Perl is a namespace in the file corresponding to that namespace. The package keyword creates the namespace. A module name My::Math maps to the file My/Math.pm. A module name A::B::C maps to the file A/B/C.pm somewhere in the directories listed in @INC.

As you recall, the use My::Math qw(add); statement in the script will load the module and then call the import function. Most people don't want to implement their own import function, so they load the Exporter module and import the 'import' function.

Yes, it is a bit confusing. The important thing to remember is that Exporter gives you the import.

That import function will look at the @EXPORT_OK array in your module and arrange for on-demand importing of the functions listed in this array.

OK, maybe I need to clarify: The module "exports" functions and the script "imports" them.

The last thing I need to mention is the 1; at the end of the module. Basically the use statement is executing the module and it needs to see some kind of a true statement there. It could be anything. Some people put there 42; , others, the really funny ones put "FALSE" there. After all every string with letters in it is considered to be true in Perl . That confuses about everyone. There are even people who put quotes from poems there.

"Famous last words."

That's actually nice, but might still confuse some people at first.

There are also two functions in the module. We decided to export both of them, but the user (the author of the script) wanted to import only one of the subroutines.

Conclusion

Aside from a few lines that I explained above, it is quite simple to create a Perl module. Of course there are other things you might want to learn about modules that will appear in other articles, but there is nothing stopping you now from moving some common functions into a module.

Maybe one more advice on how to call your module:

Naming of modules

It is highly recommended to use capital letter as the first letter of every part in the module name and lower case for the rest of the letters. It is also recommended to use a namespace several levels deep.

If you work in a company called Abc, I'd recommend preceding all the modules with the Abc:: namespace. If within the company the project is called Xyz, then all its modules should be in Abc::Xyz::.

So if you have a module dealing with configuration you might call the package Abc::Xyz::Config which indicates the file .../projectdir/lib/Abc/Xyz/Config.pm

Please avoid calling it just Config.pm. That will confuse both Perl (that comes with its own Config.pm) and you.

[Nov 06, 2017] In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file - Stack Overflow

Nov 06, 2017 | stackoverflow.com

user380979 , Aug 4, 2010 at 5:20

What is the Difference between .pm (Perl module) and .pl (Perl script) file?

Please also tell me why we return 1 from file. If return 2 or anything else, it's not generating any error, so why do we return 1 from Perl module?

Amadan , Aug 4, 2010 at 5:32

1 does not matter. It can be 2 , it can be "foo" , it can be ["a", "list"] . What matters is it's not 0 , or anything else that evaluates as false, or use would fail. – Amadan Aug 4 '10 at 5:32

Marc Lehmann , Oct 16, 2015 at 22:08

.pl is actually a perl library - perl scripts, like C programs or programs written in other languages, do not have an ending, except on operating systems that need one to functiopn, such as windows. – Marc Lehmann Oct 16 '15 at 22:08

Sinan Ünür , Aug 4, 2010 at 12:41

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC , then use and require will do the right thing when given the package name as in use Example::Plot::FourD .

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1; , in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl , loaded it in a script in file s.pl .

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1 , any true value will do.

Igor Oks , Aug 4, 2010 at 5:25

A .pl is a single script.

In .pm ( Perl Module ) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

Dave Cross , Sep 17, 2010 at 9:37

"A .pl is a single script." Not true. It's only on broken operating systems that you need to identify Perl programs with a .pl extension. And originally .pl indicated a "Perl library" - external subroutines that you loaded with a "require" or "do" command. – Dave Cross Sep 17 '10 at 9:37

[Nov 06, 2017] W>hat is difference between namespace,package and module in perl

Nov 06, 2017 | stackoverflow.com
The package directive sets the namespace. As such, the namespace is also called the package.

Perl doesn't have a formal definition of module. There's a lot of variance, but the following holds for a huge majority of modules:

It's not uncommon to encounter .pm files with multiple packages. Whether that's a single module, multiple modules or both is up for debate.

Namespace is a general computing term meaning a container for a distinct set of identifiers. The same identifier can appear independently in different namespaces and refer to different objects, and a fully-qualified identifier which unambiguously identifies an object consists of the namespace plus the identifier.

Perl implements namespaces using the package keyword.

A Perl module is a different thing altogether. It is a piece of Perl code that can be incorporated into any program with the use keyword. The filename should end with .pm - for erl odule - and the code it contains should have a package statement using a package name that is equivalent to the file's name, including its path. For instance, a module written in a file called My/Useful/Module.pm should have a package statement like package My::Useful::Module .

What you may have been thinking of is a class which, again, is a general computing term, this time meaning a type of object-oriented data. Perl uses its packages as class names, and an object-oriented module will have a constructor subroutine - usually called new - that will return a reference to data that has been blessed to make it behave in an object-oriented fashion. By no means all Perl modules are object-oriented ones: some can be simple libraries of subroutines.

[Oct 31, 2015] Coping with Scoping

perl.plover.com

... ... ...

The problem with Perl isn't that it has no clearly-defined system of name management, but rather that it two systems, both working at once. Here's the Big Secret about Perl variables that most people learn too late: Perl has two completely separate, independent sets of variables. One is left over from Perl 4, and the other is new. The two sets of variables are called `package variables' and `lexical variables', and they have nothing to do with each other.

Package variables came first, so we'll talk about them first. Then we'll see some problems with package variables, and how lexical variables were introduced in Perl 5 to avoid these problems. Finally, we'll see how to get Perl to automatically diagnose places where you might not be getting the variable you meant to get, which can find mistakes before they turn into bugs.

Package Variables
        $x = 1

Here, $x is a package variable. There are two important things to know about package variables:

  1. Package variables are what you get if you don't say otherwise.
  2. Package variables are always global.

Global means that package variables are always visible everywhere in every program. After you do $x = 1, any other part of the program, even some other subroutine defined in some other file, can inspect and modify the value of $x. There's no exception to this; package variables are always global.

Package variables are divided into families, called packages. Every package variable has a name with two parts. The two parts are analogous to the variable's given name and family name. You can call the Vice-President of the United States `Al', if you want, but that's really short for his full name, which is `Al Gore'. Similarly, $x has a full name, which is something like $main::x. The main part is the package qualifier, analogous to the `Gore' part of `Al Gore'. Al Gore and Al Capone are different people even though they're both named `Al'. In the same way, $Gore::Al and $Capone::Al are different variables, and $main::x and $DBI::x are different variables.

You're always allowed to include the package part of the variable's name, and if you do, Perl will know exactly which variable you mean. But for brevity, you usually like to leave the package qualifier off. What happens if you do?

The Current Package

If you just say $x, perl assumes that you mean the variable $x in the current package. What's the current package? It's normally main, but you can change the current package by writing

        package Mypackage;

in your program; from that point on, the current package is Mypackage. The only thing the current package does is affect the interpretation of package variables that you wrote without package names. If the current package is Mypackage, then $x really means $Mypackage::x. If the current package is main, then $x really means $main::x.

If you were writing a module, let's say the MyModule module, you would probably put a line like this at the top of the module file:

        package MyModule;

From there on, all the package variables you used in the module file would be in package MyModule, and you could be pretty sure that those variables wouldn't conflict with the variables in the rest of the program. It wouldn't matter if both you and the author of DBI were to use a variable named $x, because one of those $xes would be $MyModule::x and the other would be $DBI::x.

Remember that package variables are always global. Even if you're not in package DBI, even if you've never heard of package DBI, nothing can stop you from reading from or writing to $DBI::errstr. You don't have to do anything special. $DBI::errstr, like all package variables, is a global variable, and it's available globally; all you have to do is mention its full name to get it. You could even say

        package DBI;
        $errstr = 'Ha ha Tim!';

and that would modify $DBI::errstr.

Package Variable Trivia

There are only three other things to know about package variables, and you might want to skip them on the first reading:

  1. The package with the empty name is the same as main. So $::x is the same as $main::x for any x.
  2. Some variables are always forced to be in package main. For example, if you mention %ENV, Perl assumes that you mean %main::ENV, even if the current package isn't main. If you want %Fred::ENV, you have to say so explicitly, even if the current package is Fred. Other names that are special this way include INC, all the one-punctuation-character names like $_ and $$, @ARGV, and STDIN, STDOUT, and STDERR.
  3. Package names, but not variable names, can contain ::. You can have a variable named $DBD::Oracle::x. This means the variable x in the package DBD::Oracle; it has nothing at all to do with the package DBD which is unrelated. Isaac Newton is not related to Olivia Newton-John, and Newton::Isaac is not related to Newton::John::Olivia. Even though it appears that they both begin with Newton, the appearance is deceptive. Newton::John::Olivia is in package Newton::John, not package Newton.

That's all there is to know about package variables.

Package variables are global, which is dangerous, because you can never be sure that someone else isn't tampering with them behind your back. Up through Perl 4, all variables were package variables, which was worrisome. So Perl 5 added new variables that aren't global.

Lexical Variables

Perl's other set of variables are called lexical variables (we'll see why later) or private variables because they're private. They're also sometimes called my variables because they're always declared with my. It's tempting to call them `local variables', because their effect is confined to a small part of the program, but don't do that, because people might think you're talking about Perl's local operator, which we'll see later. When you want a `local variable', think my, not local.

The declaration

        my $x;

creates a new variable, named x, which is totally inaccessible to most parts of the program---anything outside the block where the variable was declared. This block is called the scope of the variable. If the variable wasn't declared in any block, its scope is from the place it was declared to the end of the file.

You can also declare and initialize a my variable by writing something like

        my $x = 119;

You can declare and initialize several at once:

        my ($x, $y, $z, @args) = (5, 23, @_);

Let's see an example of where some private variables will be useful. Consider this subroutine:

        sub print_report {
          @employee_list = @_;
          foreach $employee (@employee_list) {
            $salary = lookup_salary($employee);
            print_partial_report($employee, $salary);
          }
        }

If lookup_salary happens to also use a variable named $employee, that's going to be the same variable as the one used in print_report, and the works might get gummed up. The two programmers responsible for print_report and lookup_salary will have to coordinate to make sure they don't use the same variables. That's a pain. In fact, in even a medium-sized project, it's an intolerable pain.

The solution: Use my variables:

        sub print_report {
          my @employee_list = @_;
          foreach my $employee (@employee_list) {
            my $salary = lookup_salary($employee);
            print_partial_report($employee, $salary);
          }
        }

my @employee_list creates a new array variable which is totally inaccessible outside the print_report function. for my $employee creates a new scalar variable which is totally inaccessible outside the foreach loop, as does my $salary. You don't have to worry that the other functions in the program are tampering with these variables, because they can't; they don't know where to find them, because the names have different meanings outside the scope of the my declarations. These `my variables' are sometimes called `lexical' because their scope depends only on the program text itself, and not on details of execution, such as what gets executed in what order. You can determine the scope by inspecting the source code without knowing what it does. Whenever you see a variable, look for a my declaration higher up in the same block. If you find one, you can be sure that the variable is inaccessible outside that block. If you don't find a declaration in the smallest block, look at the next larger block that contains it, and so on, until you do find one. If there is no my declaration anywhere, then the variable is a package variable.

my variables are not package variables. They're not part of a package, and they don't have package qualifiers. The current package has no effect on the way they're interpreted. Here's an example:

        my $x = 17;

        package A;
        $x = 12;

        package B;
        $x = 20;

        # $x is now 20.
        # $A::x and $B::x are still undefined

The declaration my $x = 17 at the top creates a new lexical variable named x whose scope continues to the end of the file. This new meaning of $x overrides the default meaning, which was that $x meant the package variable $x in the current package.

package A changes the current package, but because $x refers to the lexical variable, not to the package variable, $x=12 doesn't have any effect on $A::x. Similarly, after package B, $x=20 modifies the lexical variable, and not any of the package variables.

At the end of the file, the lexical variable $x holds 20, and the package variables $main::x, $A::x, and $B::x are still undefined. If you had wanted them, you could still have accessed them by using their full names.

The maxim you must remember is:

Package variables are global variables.
For private variables, you must use my.

local and my

Almost everyone already knows that there's a local function that has something to do with local variables. What is it, and how does it related to my? The answer is simple, but bizarre:

my creates a local variable. local doesn't.

First, here's what local $x really does: It saves the current value of the package variable $x in a safe place, and replaces it with a new value, or with undef if no new value was specified. It also arranges for the old value to be restored when control leaves the current block. The variables that it affects are package variables, which get local values. But package variables are always global, and a local package variable is no exception. To see the difference, try this:

        $lo = 'global';
        $m  = 'global';
        A();

        sub A {
          local $lo = 'AAA';
          my    $m  = 'AAA';
          B();
        }

        sub B {
          print "B ", ($lo eq 'AAA' ? 'can' : 'cannot') ,
                " see the value of lo set by A.\n";

          print "B ", ($m  eq 'AAA' ? 'can' : 'cannot') ,
                " see the value of m  set by A.\n";
        }

This prints

        B can see the value of lo set by A.
        B cannot see the value of m  set by A.

What happened here? The local declaration in A saved a new temporary value, AAA, in the package variable $lo. The old value, global, will be restored when A returns, but before that happens, A calls B. B has no problem accessing the contents of $lo, because $lo is a package variable and package variables are always available everywhere, and so it sees the value AAA set by A.

In contrast, the my declaration created a new, lexically scoped variable named $m, which is only visible inside of function A. Outside of A, $m retains its old meaning: It refers the the package variable $m; which is still set to global. This is the variable that B sees. It doesn't see the AAA because the variable with that value is a lexical variable, and only exists inside of A.

What Good is local?

Because local does not actually create local variables, it is not very much use. If, in the example above, B happened to modify the value of $lo, then the value set by A would be overwritten. That is exactly what we don't want to happen. We want each function to have its own variables that are untouchable by the others. This is what my does.

Why have local at all? The answer is 90% history. Early versions of Perl only had global variables. local was very easy to implement, and was added to Perl 4 as a partial solution to the local variable problem. Later, in Perl 5, more work was done, and real local variables were put into the language. But the name local was already taken, so the new feature was invoked with the word my. my was chosen because it suggests privacy, and also because it's very short; the shortness is supposed to encourage you to use it instead of local. my is also faster than local.

When to Use my and When to Use local

Always use my; never use local.

Wasn't that easy?

Other Properties of my Variables

Every time control reaches a my declaration, Perl creates a new, fresh variable. For example, this code prints x=1 fifty times:

        for (1 .. 50) {
          my $x;
          $x++;
          print "x=$x\n";
        }

You get a new $x, initialized to undef, every time through the loop.

If the declaration were outside the loop, control would only pass by it once, so there would only be one variable:

        { my $x;
          for (1 .. 50) {
            $x++;
            print "x=$x\n";
          }     
        }
        

This prints x=1, x=2, x=3, ... x=50.

You can use this to play a useful trick. Suppose you have a function that needs to remember a value from one call to the next. For example, consider a random number generator. A typical random number generator (like Perl's rand function) has a seed in it. The seed is just a number. When you ask the random number generator for a random number, the function performs some arithmetic operation that scrambles the seed, and it returns the result. It also saves the result and uses it as the seed for the next time it is called.

Here's typical code: (I stole it from the ANSI C standard, but it behaves poorly, so don't use it for anything important.)

        $seed = 1;
        sub my_rand {
          $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768;
          return $seed;
        }

And typical output:

        16838
        14666
        10953
        11665
        7451
        26316
        27974
        27550

There's a problem here, which is that $seed is a global variable, and that means we have to worry that someone might inadvertently tamper with it. Or they might tamper with it on purpose, which could affect the rest of the program. What if the function were used in a gambling program, and someone tampered with the random number generator?

But we can't declare $seed as a my variable in the function:

        sub my_rand {
          my $seed;
          $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768;
          return $seed;
        }

If we did, it would be initialized to undef every time we called my_rand. We need it to retain its value between calls to my_rand.

Here's the solution:

        { my $seed = 1;
          sub my_rand {
            $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768;
            return $seed;
          }
        }

The declaration is outside the function, so it only happens once, at the time the program is compiled, not every time the function is called. But it's a my variable, and it's in a block, so it's only accessible to code inside the block. my_rand is the only other thing in the block, so the $seed variable is only accessible to the my_rand function.

$seed here is sometimes called a `static' variable, because it stays the same in between calls to the function. (And because there's a similar feature in the C language that is activated by the static keyword.)

my Variable Trivia
  1. You can't declare a variable my if its name is a punctuation character, like $_, @_, or $$. You can't declare the backreference variables $1, $2, ... as my. The authors of my thought that that would be too confusing.
  2. Obviously, you can't say my $DBI::errstr, because that's contradictory---it says that the package variable $DBI::errstr is now a lexical variable. But you can say local $DBI::errstr; it saves the current value of $DBI::errstr and arranges for it to be restored at the end of the block.
  3. New in Perl 5.004, you can write

            foreach my $i (@list) {
    

    instead, to confine the $i to the scope of the loop instead. Similarly,

            for (my $i=0; $i<100; $i++) { 
    

    confines the scope of $i to the for loop.

Declarations

If you're writing a function, and you want it to have private variables, you need to declare the variables with my. What happens if you forget?

        sub function {
          $x = 42;        # Oops, should have been my $x = 42.
        }

In this case, your function modifies the global package variable $x. If you were using that variable for something else, it could be a disaster for your program.

Recent versions of Perl have an optional protection against this that you can enable if you want. If you put

        use strict 'vars';

at the top of your program, Perl will require that package variables have an explicit package qualifier. The $x in $x=42 has no such qualifier, so the program won't even compile; instead, the compiler will abort and deliver this error message:

        Global symbol "$x" requires explicit package name at ...

If you wanted $x to be a private my variable, you can go back and add the my. If you really wanted to use the global package variable, you could go back and change it to

        $main::x = 42;

or whatever would be appropriate.

Just saying use strict turns on strict vars, and several other checks besides. See perldoc strict for more details.

Now suppose you're writing the Algorithms::KnuthBendix modules, and you want the protections of strict vars But you're afraid that you won't be able to finish the module because your fingers are starting to fall off from typing $Algorithms::KnuthBendix::Error all the time.

You can save your fingers and tell strict vars to make an exception:

        package Algorithms::KnuthBendix;
        use vars '$Error';

This exempts the package variable $Algorithms::KnuthBendix::Error from causing a strict vars failure if you refer to it by its short name, $Error.

You can also turn strict vars off for the scope of one block by writing

        { no strict 'vars';

          # strict vars is off for the rest of the block.

        }

Summary

Package variables are always global. They have a name and a package qualifier. You can omit the package qualifier, in which case Perl uses a default, which you can set with the package declaration. For private variables, use my. Don't use local; it's obsolete.

You should avoid using global variables because it can be hard to be sure that no two parts of the program are using one another's variables by mistake.

To avoid using global variables by accident, add use strict 'vars' to your program. It checks to make sure that all variables are either declared private, are explicitly qualified with package qualifiers, or are explicitly declared with use vars.


Glossary
Notes
  1. The tech editors complained about my maxim `Never use local.' But 97% of the time, the maxim is exactly right. local has a few uses, but only a few, and they don't come up too often, so I left them out, because the whole point of a tutorial article is to present 97% of the utility in 50% of the space.

    I was still afraid I'd get a lot of tiresome email from people saying ``You forgot to mention that local can be used for such-and-so, you know.'' So in the colophon at the end of the article, I threatened to deliver Seven Useful Uses for local in three months. I mostly said it to get people off my back about local. But it turned out that I did write it, and it was published some time later.

    The Seven Useful Uses of local is now available on the web site. It appeared in The Perl Journal issue #14.

  2. Here's another potentially interesting matter that I left out for space and clarity. I got email from Robert Watkins with a program he was writing that didn't work. The essence of the bug looked like this:
            my $x;
    
            for $x (1..5) {
              s();
            }
    
            sub s { print "$x, " }
    

    Robert wanted this to print 1, 2, 3, 4, 5, but it did not. Instead, it printed , , , , , . Where did the values of $x go?

    The deal here is that normally, when you write something like this:

                        for $x (...) { }
    

    Perl wants to confine the value of the index variable to inside the loop. If $x is a package variable, it pretends that you wrote this instead:

            { local $x; for $x (...) { } }
    

    But if $x is a lexical variable, it pretends you wrote this instead, instead:

            { my $x;    for $x (...) { } }
    

    This means that the loop index variable won't get propagated to subroutines, even if they're in the scope of the original declaration.

    I probably shouldn't have gone on at such length, because the perlsyn manual page describes it pretty well:

    ...the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. (Note that a lexically scoped variable can cause problems if you have subroutine or format declarations within the loop which refer to it.)

    In my opinion, lexically scoping the index variable was probably a mistake. If you had wanted that, you would have written for my $x ... in the first place. What I would have liked it to do was to localize the lexical variable: It could save the value of the lexical variable before the loop, and restore it again afterwards. But there may be technical reasons why that couldn't be done, because this doesn't work either:

    	my $m;
    	{ local $m = 12;
    	  ...
    	}
    

    The local fails with this error message:

    	Can't localize lexical variable $m...
    

    There's been talk on P5P about making this work, but I gather it's not trivial.

  3. Added 2000-01-05: Perl 5.6.0 introduced a new our(...) declaration. Its syntax is the same as for my(), and it is a replacement for use vars.

    Without getting into the details, our() is just like use vars; its only effect is to declare variables so that they are exempt from the strict 'vars' checking. It has two possible advantages over use vars, however: Its syntax is less weird, and its effect is lexical. That is, the exception that it creates to the strict checking continues only to the end of the current block:

            use strict 'vars';
            {
              our($x);
              $x = 1;   # Use of global variable $x here is OK
            }
            $x = 2;     # Use of $x here is a compile-time error as usual
    

    So whereas use vars '$x' declares that it is OK to use the global variable $x everywhere, our($x) allows you to say that global $x should be permitted only in certain parts of your program, and should still be flagged as an error if you accidentally use it elsewhere.

  4. Added 2000-01-05: Here's a little wart that takes people by surprise. Consider the following program:
            use strict 'vars';
            my @lines = <>;
            my @sorted = sort backwards @lines;
            print @sorted;
    
            sub backwards { $b cmp $a }
    

    Here we have not declared $a or $b, so they are global variables. In fact, they have to be global, because the sort operator must to be able to set them up for the backwards function. Why doesn't strict produce a failure?

    The variables $a and $b are exempted from strict vars checking, for exactly this reason.

http://perl.plover.com/FAQs/Namespaces.html

'our' is not 'my'

Update: At the request of a couple of people, some as replies to this node and one as a private message, I have added a link to this node from the Tutorials section. I have linked it rather than repost it to tutorials as there is no reason for me to get the rep twice. I might add that I would not have done this were it not for the high rep this node has received (thus suggesting to me that monks find this information useful).

Many people misunderstand how our is used and I've often seen code where it's used as a synonym for my. This is not the case and I hope this clears up some of the differences. I'm posting this because I've run across this a few times lately and I thought I should just 'get it out there' for others.

There are basically two ways of declaring variables in Perl: global and lexical. A global variable has a package name prepending to it:

$main::foo; $CGI::POST_MAX; @foo::bar;

[download]

All packages can access the variable $foo in the main symbol table (%main:: or the shorthand %::) by using $main::foo. Global variables are generally a bad idea, but do crop up in a lot of code.

A lexically scoped variable is declared with my:

my $foo; my $POST_MAX; my @bar;

[download]

Though they look similar to the package variables above, they are not the same and cannot be accessed outside of the scope in which they were declared.

If you use strict and you try to access a variable that's not previously declared, you'll get an error similar to the following:

Global symbol "$foo" requires explicit package name at C:\test.pl +line 2.

[download]

Basically, Perl expects that you are trying to use a package variable, but left off the package name. The problem with using package names ($main::foo) is that strict ignores these variables and if you type $main::field in one place and $main::feild in another place, strict won't warn you of the typo.

our tries to help out by letting you use package variables without adding the package name. The following two variables are the same:

package foo; use strict; our $bar; # These are the same $foo::bar; # These are the same

[download]

That eliminates the $main::f(ie|ei)ld problem by allowing you to do this:

our $field;

[download]

From there, you just drop package names and the script will run and later Perl will kill the script if you try use $feild. Unfortunately, there are a lot of problems with this.

The main problem is that you are now using global variables which is generally a Bad Thing. Any code, anywhere, can change your global. Large systems with lots of globals typically suffer this problems and quickly become unmaintainable.

This also leads to very subtle coding errors. Try the following code:

use strict; for ( 1 .. 3 ) { &doit } sub doit { our $foo; print ++$foo . "\n"; }

[download]

That will print 1, 2, and 3 on successive lines. Change the our to a my and it prints 1, 1, and 1. Because the my variable goes out of scope at the end of the sub and the our variable doesn't (since it's global), you get wildly different results.

There is one use I have found for our variables. if I am forced to maintain a large code base with lots of global variables, I usually expect to see lots of code problems, including misspellings of those globals that are overlooked due to the hacked nature of those code. For example, one site I worked on had some object-oriented code that stuffs a lot of data into package main (you can keep reading after you stop laughing). I've seen code like this:

$main::sql = $order->lineItemSQL; $main::dbh->prepare( $main::sql );

[download]

 

I know, it doesn't make a lot of sense (why doesn't it just return the line items instead of the SQL?), but I needed to clean up stuff like that. So, in my code, I put the following:

 
our ( $sql, $dbh ); #later $sql = $order->lineItemSQL; $dbh->prepare( $sql );

[download]

 

I didn't convert them to my variables because these variables were being declared in another package.

This doesn't seem like much benefit aside from eliminating a few bytes (and it certainly wasn't the best solution, but we've all had time constraints...). However, there is a huge benefit. Later in the code, when we encounter $main::slq, it becomes $slq and the program dies a much needed death.

As a side note: the primary difference (that I can see) between our and use vars appears to be that our lexically scopes the use of the variable name (not the variable) and the other does not. The following code snippets should clarify that:

 
use strict; { use vars qw/ $foo /; $foo = "Ovid"; } print $foo;

[download]

 

That code will work fine. However, change the use vars qw/ $foo /; to our $foo and Perl dies, telling you that $foo requires an explicit package name. However, change the print statement to include the package name and all is well:

 
use strict; { our $foo; $foo = "Ovid"; } print $main::foo;

[download]

This behavior may not seem immediately useful, but you can then use an our declaration at the top of a subroutine, strip off the package names in the sub, and not worry about this conflicting with my variables in the rest of the code.

use strict; my $foo = 'bar'; &baz; sub baz { our $foo = 7; print $foo; } print $foo;

[download]

Change that code to use "use vars" and you'll see it print 7 twice, stepping on your my variable.

Interesting to note that the only uses I've found for our have been hacking bad code...

Cheers,
Ovid

Scope of variables in Perl

There are two major variable types in Perl. One of them is the package global variable declared either with the now obsolete use vars construct or with our.

The other one is the lexical variable declared with my.

Let's see what happens when you declare a variable using my? In which parts of the code will that variable be visible? In other words, what is the scope of the variable?

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. {
  5. my $email = 'foo@bar.com';
  6. print "$email\n"; # foo@bar.com
  7. }
  8. # print $email;
  9. # $email does not exists
  10. # Global symbol "$email" requires explicit package name at ...

Inside the anonymous block (the pair of curly braces {}), first we see the declaration of a new variable called $email. This variable exists between the point of its declaration till the end of the block. Thus the line after the closing curly brace } had to be commented out. If you removed the # from the # print $email; line, and tried to run the script, you'd get the following compile-time error: Global symbol "$email" requires explicit package name at ....

In other words, the scope of every variable declared with my is the enclosing block..

Variable scope: visible everywhere

The variable $lname is declared at the beginning of the code. It will be visible till the end of the file everywhere. Even inside blocks. Even if those are function declarations. If we change the variable inside the block, that will change the value for the rest of the code. Even when you leave the block:

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. my $lname = "Bar";
  5. print "$lname\n"; # Bar
  6. {
  7. print "$lname\n"; # Bar
  8. $lname = "Other";
  9. print "$lname\n"; # Other
  10. }
  11. print "$lname\n"; # Other

Variable hidden by other declaration

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. my $fname = "Foo";
  5. print "$fname\n"; # Foo
  6. {
  7. print "$fname\n"; # Foo
  8. my $fname = "Other";
  9. print "$fname\n"; # Other
  10. }
  11. print "$fname\n"; # Foo
 

In this case the variable $fname is declared at the beginning of the code. As written earlier, it will be visible till the end of the file everywhere, except in places where they are hidden by locally declared variables with the same name.

Inside the block we used my to declare another variable with the same name. This will effectively hide the $fname declared outside the block till we leave the block. At the end of the block (at the closing }), the $fname declared inside will be destroyed and the original $fname will be accessible again. This feature is especially important as this makes it easy to create variables inside small scopes without the need to think about possible use of the same name outside.

Same name in multiple blocks

You can freely use the same variable name in multiple block. These variables have no connection to each other.

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. {
  5. my $name = "Foo";
  6. print "$name\n"; # Foo
  7. }
  8. {
  9. my $name = "Other";
  10. print "$name\n"; # Other
  11. }

In-file package declaration

This a bit more advanced example, but it might be important to mention it here:

Perl allows us to switch between name-spaces using the package keyword inside a file. A package declaration does NOT provide scope. If you declare a variable in the implicit main package which is just the regular body of your script, that $fname variable will be visible even in other name-spaces in the same file.

If you declare a variable called $lname in the 'Other' name-space, it will be visible when later you might switch back to the main name-space. If the package Other declaration was in another file, then the variables would have separate scope created by the file.

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. my $fname = "Foo";
  5. print "$fname\n"; # Foo
  6. package Other;
  7. use strict;
  8. use warnings;
  9. print "$fname\n"; # Foo
  10. my $lname = 'Bar';
  11. print "$lname\n"; # Bar
  12. package main;
  13. print "$fname\n"; # Foo
  14. print "$lname\n"; # Bar