Hello all,
I have a question regrading the best practices for scoping variables in a sub routine. The way I see it there are two ways I can pass variables to and from a sub routine, either by making them global as in:
Or is it best practice to keep the vars local and pass them as in:
As always, any thoughts are appriciated.
Nick
I have a question regrading the best practices for scoping variables in a sub routine. The way I see it there are two ways I can pass variables to and from a sub routine, either by making them global as in:
Code:
my ($var1, @arr1, $var2);
# Start main
while (<FILE>) {
NewSub();
my $new_var = $var1;
print "$new_var\n"; # will print 4 because var1 is global
}
sub NewSub
{
$var1 = (2 + 2);
}
Or is it best practice to keep the vars local and pass them as in:
Code:
while (<FILE>) {
my $new_var = NewSub();
print "$new_var\n"; # will print 4 again but var remains local
}
sub NewSub
{
my $var1 = (2 + 2);
return $var1;
}
As always, any thoughts are appriciated.
Nick