I want to create a static variable in my module. How can I do that? Can I use our
or state
?
Here is an example of what I want to achieve:
use MyModule;
MyModule::increase_count(); # should return 0
MyModule::increase_count(); # should return 1
MyModule::increase_count(); # should return 2
If you want to use state
(which is a good idea):
package MyModule;
# return the previous value
sub increase_count {
state $count = 0;
return $count++;
}
Using state
minimizes the visibility of the symbol. If you have to share the visibility accross multiple subs, you can enclose a lexical variable in a block:
{
my $count = 0;
sub increase_count { $count++ }
sub current_count { $count }
sub decrease_count { $count-- }
}
If you want to access $counter
variable directly outside of MyModule
package, use our
, but if you don't then my
is what should be used,
package MyModule;
my $counter = 0;
sub increase_count {
return $counter++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.