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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Global/Local variable 1

Status
Not open for further replies.

ejaggers

Programmer
Feb 26, 2005
148
US
I'd like to save a value in $LastValue, but don't want it to be global, or disappear when I exit the subroutine like my $LastValue. Is there such a type that will stay set but is not global?
 
Probably the easiest way is to return the value you want to keep from the sub. There's not much context, so it's hard to tell.

A quick example:
Code:
my $last_value = mysub();
print "Value from sub: $last_value\n";

sub mysub {
  # do stuff
  return $value;
}
 
rharsh, what I mean is:

sub xyz {
my $x = shift;
$x = $Last_Value unless $x;
$Last_Value = $x;
...

return;
}

Is there a way to save $Last_Value in sub xyz, without making it global to all?

 
I don't believe this is possible and it was one of the things Perl 6 is going to address.

What you could do is create a unique package for your subroutine and use it as a class-level variable.

i.e.

Code:
package MyXYZ;

use Exporter;
@EXPORT = ("xyz");

our $Last_Value = 0;
sub xyz {
   # ...whatever
   $Last_Value = $z;
}

package main;
use MyXYZ;

# continue your main code here

print "last value: $Last_Value\n"; # shouldn't work
xyz ($whatever);
print "last value: $Last_Value\n"; # shouldn't work
print "again: $MyXYZ::Last_Value\n"; # if you really really want it

If you don't like mixing multiple packages in the same source file you can save it like a Perl module.

Cuvou.com | My personal homepage
Code:
perl -e '$|=$i=1;print" oo\n<|>\n_|_";x:sleep$|;print"\b",$i++%2?"/":"_";goto x;'
 
Thanks perx1, I've been using globals all over the place. This is a BIG help!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top