#!/usr/bin/perl #============================================================================== =pod =head1 NAME counter.pm =head1 VERSION 1.0 =head1 DESCRIPTION This module contains the class counter. It stores an id and a value for this counter. =head1 AUTHOR Mein Name I =head1 CREATED 2011-05-12 =head1 LAST MODIFIED 2011-05-13 =cut #============================================================================== use strict; use warnings; use v5.10.0; # 'say' and some other nice features package Counter; use overload '~~' => \&_match, # Overload ~~ for easier matching '+' => \&_add, # Overload + for easier value adding. '""' => \&_stringify; # Overload "" for correct printing # Create a new counter with an id. Initialize value with 0 sub new { my ( $class, $id ) = @_; my $self = {}; $self->{'id'} = $id; $self->{'value'} = 0; bless( $self, $class ); return $self; } ############################################################################## # A generic getter. Return the value of the attribute. # # example: # my $value = my_counter->get('id'); # # parameters: # $attr - The attribute to return. ############################################################################## sub get { my ( $self, $attr ) = @_; return $self->{$attr}; } ############################################################################## # A generic setter. Set the value of a given attribute. # # example: # my_counter->set('value', 200); # # parameters: # $attr - The attribute to set. # $value - The value to set for the attribute. ############################################################################## sub set { my ( $self, $attr, $value ) = @_; $self->{$attr} = $value; } ############################################################################## # Add a number to the counter value. # Don't use this method directly. Use the '+' operator instead. # # example: # my_counter += 100; # # parameters: # $number - The number to add to value. ############################################################################## sub _add { my ( $self, $number ) = @_; my $new_counter = Counter->new( $self->get('id') ); if ( ref $number ) { $new_counter->set( 'value', $self->get('value') + $number->get('value') ); } else { $new_counter->set( 'value', $self->get('value') + $number ); } return $new_counter; } sub _match { my ( $self, $id ) = @_; return $self->get('id') ~~ $id; } sub _stringify { my $self = shift; return $self->get('value'); } 1;