1

i have an array called @missing_ports this array has been updating from different subroutines and loops. So array need to be global. how to define this array as global in perl. code contains use warnings; use strict;

i declared this array in start of the program without "my" keyword, facing below error @missing_ports" requires explicit package name at experiment.pl with my keyword able to resolve the error but array is null in the end.

how can manage this situation in perl?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.