1

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.

2
  • 1
    my variables are, by definition, not global. At most, a my variable may have file scope. Commented Apr 15, 2014 at 13:14
  • 2
    In general it is bad practice to rely on and modify globals. Instead, pass parameters and return values. $variable = change($variable); is a much better coding style for most use cases. Commented Apr 15, 2014 at 18:53

1 Answer 1

2

Just assign to it:

sub change { 
   $global = 'bar';
}

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

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.