Bootstrap FreeKB - Perl (Scripting) - Global and lexical variables (my and our)
Perl (Scripting) - Global and lexical variables (my and our)

Updated:   |  Perl (Scripting) articles

In Perl, if use strict and use warnings are used (they should!), variables must then be defined using my.

#!/usr/bin/perl
use strict;
use warnings;
my $foo = "bar";

 

Or using our.

#!/usr/bin/perl
use strict;
use warnings;
our $foo = "bar";

 

Global variables can be used anywhere in your Perl script, where a lexical variable can only be used within a lexical scope. Take for example the following script. In this example, a lexical variable inside of a subroutine is created and is used within it's lexical scope (within the subroutine).

#!/usr/bin/perl
use strict;
use warnings;

sub example {
  my $foo = "bar";
  print $foo;
}

example();

 

This script will not produce any errors, and the text "bar" will be printed.

bar

 

Similarly, take for example the following. In this example, the $foo variable is consider global because it is not within any lexical scopes (such as a subroutine or if statement). When the $foo variable is used within a lexical scope, the example subroutine, the variable can be used.

#!/usr/bin/perl
use strict;
use warnings;

my $foo = "bar";

sub example {
  print "$foo\n";
}

example();      

 

This script will not produce any errors, and the text "bar" will be printed.

bar

 

However, error "Global symbol "$foo" requires explicit package name" will be returned when attempting to print the lexical variable outside of the subroutine, because lexical variables must be used inside of the subroutine (that's the scope).

#!/usr/bin/perl

use strict;
use warnings;

sub example {
  my $foo = "bar";
}

example();

print $foo;

 

The solution to this is easy. You simply create the variable at the highest scope that the variable will be used. Then, when you want to use the variable inside of a nested scope, such as in a subroute or an if statement, you no longer use my or our when using the variable throughout the script. Take for example the following scipt. $foo is created outside of the example subroutine. Inside of the example subroutine, $foo is given a value of bar. $foo is then used outside of the subroutine.

#!/usr/bin/perl

use strict;
use warnings;

my $foo = "";

sub example {
  $foo = "bar";
}

example();

print $foo;

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 26a66a in the box below so that we can be sure you are a human.