Why can't my Perl script see the our() variables I defined in another file?

perl, require, scope

Solution

There's no `require` statement in your second example, but it wouldn't work anyway. What `our` does is declare a lexically-scoped package variable. Since you have no `package` statement, it uses the default package `main`. So your first script sets up the variable `$main::var1`, but this will only be available within that file's scope.

A better way to provide common variables for other scripts is to use Exporter. You can define package symbols in one place and Exporter will take care of copying them to the requesting script or class's namespace when needed.

Problem

I have a question relating to Perl and scoping. I have a common file with lots of various variables. I require the common file in my main script, but I cannot access the variables; they seem to be outside of its scope. I assumed that an `our` declaration would overcome that problem, but it doesn't seem to work. Script 1: common.pl ``` #!/usr/bin/perl our $var1 = "something"; our $var2 = "somethingelse"; ``` Script 2: ftp.pl ``` #!/usr/bin/perl use strict; use warnings; require('common.pl'); print $var1; ``` I get the error: ``` Global symbol "$var1" requires explicit package name ```

Original source