package AN::Tut::Tools::Math; # This sets the version of this file. It will be useful later. BEGIN { our $VERSION="0.1.001"; } # This just sets perl to be strict about how it runs and to die in a way # more compatible with the caller. use strict; use warnings; use Carp; # The constructor method. sub new { my $class=shift; my $self={ HANDLE_TUT_TOOLS => "" }; bless ($self, $class); return ($self); } # Get a handle on the AN::Tut::Tools object. I know that technically that is a # sibling module, but it makes more sense in this case to think of it as a # parent. sub _parent { my $self=shift; my $parent=shift; $self->{HANDLE_TUT_TOOLS}=$parent if $parent; return ($self->{HANDLE_TUT_TOOLS}); } # My addition method sub add { # I expect this to be called via the object returned by the constructor # method. The next two arguments are the two numbers to sum up. my $self=shift; my $num1=shift; my $num2=shift; # Make sure that this method is called via the module's object. croak "The method 'add' must be called via the object returned by 'new'.\n" if not ref($self); # Just a little sanity check. if (($num1 !~ /(^-?)\d+(\.\d+)?/) || ($num2 !~ /(^-?)\d+(\.\d+)?/)) { croak "The method 'AN::Tut::Sample2->add' needs to be passed two numbers.\n"; } # Do the math. my $result=$num1 + $num2; # Return the results. return ($result); } # My subtraction method sub subtract { # I expect this to be called via the object returned by the constructor # method. Then I expect a number followed by the number to subtract # from it. my $self=shift; my $num1=shift; my $num2=shift; # Make sure that this method is called via the module's object. croak "The method 'subtract' must be called via the object returned by 'new'.\n" if not ref($self); # Just a little sanity check. if (($num1 !~ /(^-?)\d+(\.\d+)?/) || ($num2 !~ /(^-?)\d+(\.\d+)?/)) { croak "The method 'AN::Tut::Sample2->subtract' needs to be passed two numbers.\n"; } # Do the math. my $result=$num1 - $num2; # Return the results. return ($result); } # My addition method that calls say on it's own. sub add_and_say { # I expect this to be called via the object returned by the constructor # method. The next two arguments are the two numbers to sum up. my $self=shift; my $num1=shift; my $num2=shift; my $lang=defined $_[0] ? shift : "en"; # Make sure that this method is called via the module's object. croak "The method 'add' must be called via the object returned by 'new'.\n" if not ref($self); # I use this object to get access to my sibling module's methods. my $an=$self->_parent; # Call a method in this module, but use the object from 'parent' # instead of 'self'. my $result=$an->Math->add($num1, $num2); # Call $an->Say to print the result. my $say_result=$an->Say->math({ lang => "$lang", task => "add", num1 => $num1, num2 => $num2, result => $result }); # Return the results. return ($say_result); } 1;