February 2012
Intermediate to advanced
1184 pages
37h 17m
English
Here’s a simple Tie::Counter class, inspired by the CPAN module of the same name.
Variables tied to this class increment themselves by 1 every time
they’re used. For example:
tie my $counter, "Tie::Counter", 100;
@array = qw /Red Green Blue/;
for my $color (@array) { # Prints:
print " $counter $color\n"; # 101 Red
} # 102 Green
# 103 BlueThe constructor takes as an optional extra argument the first value of the counter, which defaults to 0. Assigning to the counter will set a new value. Here’s the class:
package Tie::Counter;
sub FETCH { ++ ${ $_[0] } }
sub STORE { ${ $_[0] } = $_[1] }
sub TIESCALAR {
my ($class, $value) = @_;
$value = 0 unless defined $value;
bless \$value => $class;
}
1; # if in moduleSee how small that is? It doesn’t take much code to put together a class like this.
Read now
Unlock full access