Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scoping of vars in subroutines 3

Status
Not open for further replies.

nfaber

Technical User
Oct 22, 2001
446
US
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:

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
 
Code:
my $new_var=NewSub($var1, $var2);

sub NewVar {
my ($mantissa, $exponent)=@_;
my $var1=$mantissa*$exponent;
return $var1;
}

--Paul

cigless ...
 
Thanks for the reply Paul, but while you code works fine, it does not really answer my question.
 
best practice would be to always pass your vars in and out, rather than depending on global scoping. This is particularly beneficial when working on larger projects, because even if you're the only developer, something you did six weeks ago could now start impacting the code you're writing today..

Note, I'm not saying it will, but it might ;-)

HTH
--Paul

cigless ...
 
best practice would be to always pass your vars in and out, rather than depending on global scoping. This is particularly beneficial when working on larger projects, because even if you're the only developer, something you did six weeks ago could now start impacting the code you're writing today..

Note, I'm not saying it will, but it might ;-)

HTH
--Paul

cigless ...
 
I agree with Paul. Avoid global scoping as much as possible, it will make life easier in the long run. If you have a short script that is very simple and maybe uses only a sub or two, then its no big deal.
 
Thanks for the replies. Local scoping makes sense. The scripts I am writting now are much larger and more complicated than I have done in the past.
 
and always use strict! It forces you to use best principles - you would not be able to do your original code if you did "use strict".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top