in reply to converting libraries into modules
What happened in your case was that you tried to divide the first argument in @_ in your 'half' sub by two. However, if you use 'half' as a method call (i.e. $m->half(10), instead of half(10)), the first argument is the $m object (sometimes called the 'invocant'), not the number 10.package MyModule; # 'constructor' sub new { # if you call MyModule->new, $_[0] will be 'MyModule' my $class = shift; # $self can be any reference, but usually a hash my $self = {}; # this is the 'magic' that creates the object bless $self, $class; return $self; } sub half { # if you call $m->half(10), $_[0] will be the object my ( $self, $number ) = @_; # proceed as normal return $number / 2; } package main; # now no longer in package, but in script # instantiate object, call constructor my $m = MyModule->new; # yields '5' print $m->half(10);
|
|---|