Main Navigation


Scoping and Variables in Perl

Learn Perl Now!
And get a job doing Perl.


Someone once said that time is defined as Nature’s way of preventing everything from happening all at once. Likewise, scoping is Perl’s way of making sure not all variables with the same name are the same. It is not unique to Perl - most modern programming languages have some concept of scoping.

The definitive explanation of scoping in Perl is Mark Jason Dominus’s “Coping with Scoping”, which was published in the Perl Journal and is hosted on his site. We recommend that you read it for general understanding.

If you've talked about Perl code you've written in various forums you've likely received the advice that you should add “use strict;” and “use warnings;” at the top of your code. While you indeed should add these statements because they catch many common programming mistakes, you may notice that after you add them you get something like: “Global symbol "$filename" requires explicit package name at line 6.”. This error (which is admittedly not phrased very well, and is kept like that due to historical reasons) means that you haven’t declared the variable. To fix it, you need to declare the variable using "my $filename = [VALUE];" in order to first use it.