Perl function FAQ: How do I make variables private to my Perl function?
Answer: Just use the Perl my
operator. Here's an example that shows how to create a variable named bar
that is private to the function name foo
:
sub foo { my $bar = 'bar'; # # more code here ... # }
When you use the my
operator before the name of a variable, you make that variable private to the current scope. In this case the current scope is the method named foo
, so bar
is private to that function, and can't be accessed outside of foo
.
Example Perl code
Here's some working sample Perl code that shows this in action. Outside of my function I first set the value of a variable named $bar
to the string "INIT". Then, in my function/subroutine, I set the value of $bar
to the test "INIT". Then, after my subroutine I print the value of $bar
. Before looking at the answer down below, what do you think the print
statement will print?
$bar = 'INIT'; sub foo { my $bar = 'BAR'; } print "$bar\n";
If you save this Perl code to a file and then run it, the output will be:
INIT
The bar
variable you created in the function foo
remains private to that function.