Global and lexical variables in Perl

Home > Search
  by

There are two common ways to create a variable, to either use my or ot not use my. When my is not used, the variable will be global.

# Global
$i = 0;

 

When my is used, the variable will be lexical.

# Lexical
my $i = 0;

 

Global variables can be used anywhere in your Perl script, where a lexical variable can only be seen within a lexical scope. Take for example the following script. In this example, a lexical variable inside of a subroutine is created. This script will not produce any errors, and the text "Hello World" will be printed.

#!/usr/bin/perl

use strict;
use warnings;

sub example {
  my $i = "Hello World";
  print $i;
}

example();

 

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

Hello

 

However, error "Global symbol "$i" requires explicit package name at example.pl line 13" 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 $i = "Hello World";
}

example();

print $i;

 

The solution to this is easy. You simply create the variable at the very beginning of your script (initialization), and then you no longer use my when using the variable throughout the script.

#!/usr/bin/perl

use strict;
use warnings;

my $i = "";

sub example {
  $i = "Hello World";
}

example();

print $i;

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments