Global and lexical variables in Perl

Home > Search

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 markup.

sub example {
     $i = "Hello";
  my $x = "World";


print $i;
print $x;


In this example, two variables are created inside of a subroutine called example. The $i variable is global, and the $x variable is lexical. When the subroutine is called, only "Hello" will be printed, because $i is a global variable that can be used anywhere in the Perl script. World is not printed, because $x is a lexical variable. The only way to print $x would to place the print statement inside of the example subroutine.



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.