how to define array/list as global in Perl?

Solution 1:

The following creates a lexical variable:

my @missing_ports;

If it's placed the start of a file, the variable will be visible to the entire file.


The following creates a lexical variable that's aliased to a package (global) variable:

our @missing_ports;

You can use this in multiple places in the same package.

You will still need to use the variable's full name from other packages.


The following declares the package variable:

use vars qw( @missing_ports );

This is not lexically scoped.

You will still need to use the variable's full name from other packages.


And of course, you could always use the full name of the variable.

$main::missing_ports

This requires no declaration, but will warn if only referenced by name once. So it's better to combine it with our or use vars.


Punctuation variables (e.g. $_) are "super globals". Use of these variables without a package name doesn't default to a variable in the current package; it defaults to a variable in the root/main namespace. (e.g. package Foo; $x; $_; means package Foo; $Foo::x; $main::_;.) There's no means of making additional superglobals.


As a final note, all the approaches listed here other than my are extremely strong indications of bad code.