Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to define array/list as global in Perl?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading