HobbitOfShire
HobbitOfShire

Reputation: 2424

Change global variable value in PERL subroutine

I am new with PERL and i am having this use case

#global variable
my $global = "foo";
print $global . "\n";
#subroutine call
&change($global);
print $global . "\n";

Here is my subroutine

sub change { 
               change the value of global to "bar";
               return $global;
           }

And here is what i want in my output

foo
bar

I know it is basic but i really want to understand the proper way to do this in Perl.

Upvotes: 1

Views: 3796

Answers (1)

perreal
perreal

Reputation: 98118

Just assign to it:

sub change { 
   $global = 'bar';
}

and you don't need the & before the function name, change() is enough.

Upvotes: 2

Related Questions