Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their FunctionsUsing Variables from a Different Namespace

3.2.3. Using Variables from a Different Namespace

It is also possible to use the global variables of different packages. However, such variables need to be declared using the use vars qw($myvar1 @myvar2) construct.

Here's an example for a module that defines a variable and another one that access it:

# This file is MyVar.pm
#
package MyVar;

use strict;
use warnings;

# Declare a namespace-scoped variable named $myvar.
use vars qw($myvar);

sub print_myvar
{
    print $myvar, "\n";
}

1;
#!/usr/bin/perl

use strict;
use warnings;

use MyVar;

$MyVar::myvar = "Hello";

MyVar::print_myvar();

$MyVar::myvar = "World";

MyVar::print_myvar();

Written by Shlomi Fish