Izza
Izza

Reputation: 2419

Correct Way of Updating a Perl Global Variable

I have the following global in variable in file_1.pl, in package main:

package main;

my $var = -1;

If I need to update this variable from another perl file, what is the way of doing it? I tried:

$main::var = 1

But it did not work.

What is the correct way of doing it?

Thank You!

Upvotes: 2

Views: 3060

Answers (3)

brian d foy
brian d foy

Reputation: 132812

The my makes a lexical variable. It's scoped to it's block, or, if not in a block, to the file. They can't be seen outside of their scope.

You could create a global variable, as other answers have shown:

our $var;

However, a better way is to give other parts of the code an interface to updating the lexical version:

my $private;

sub set_private { $private = shift }

However, if you are going to do that, you might as well have an interface for getting the value too. Now that variable only needs to be in the same scope as the subroutines that use it, so you can hide it from the rest of the file:

{
my $private;
sub set_private { $private = shift }

sub get_private { $private }
}

Now you're just one step away from an object (in this case, a singleton):

use v5.12;

package Foo {
    my $private;
    sub new { bless \$private, shift }
    sub set { my $self = shift; $$self = shift; }

    sub get { my $self = shift; $$self; }
    }

Upvotes: 8

Nikhil Jain
Nikhil Jain

Reputation: 8342

you have to declare the variable with our otherwise it would be considered as lexical variable so change it like

our $var = -1; 

Upvotes: 3

rouzier
rouzier

Reputation: 1180

You can create a wrapper function.

In main file

our $var;
sub updateGlobal {
   $var = shift;
}

In the other file just call a function

updateGlobal(1);

Upvotes: 1

Related Questions