I'm letting you access the raw value of the counter through hash syntax so you don't need to use Exporter. You could also put everything from package StaticCtr to just before package main into another file, StaticCtr.pm (end it with 1;). Then you can use StaticCtr; in any of your programs.
The new subroutine could be just a line really, it is longer so you can play with it more (see the perlobj manual).
This prints:#!/usr/bin/perl package StaticCtr; sub new { my $this = shift; my $class = ref($this) || $this; my $self = {}; bless($self, $class); $self->{ctr} = 0; return $self; } sub inc { my $self = shift; $self->{ctr}++; return $self->{ctr}; } package main; my $c = new StaticCtr; for (1..6) { print " incremented to: " . $c->inc . "\n"; } print "Final value is " . $c->{ctr} . "\n";
[mattr@taygeta perlmonks]$ ./ctr.pl incremented to: 1 incremented to: 2 incremented to: 3 incremented to: 4 incremented to: 5 incremented to: 6 Final value is 6
In reply to Re: Making a variable in a sub retain its value between calls
by mattr
in thread Making a variable in a sub retain its value between calls
by crashtest
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |