You're almost there. Here's how to define the object and methods:
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);
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.

Hence, the return value (being whatever you pulled off $_[0]) is the object, which, when printed out, yields Package=REFTYPE(address), in your case Mymodule=HASH(0xbd5068). Instead, you will want to divide the second argument, which is why, conventionally, people will copy from @_ like so: my ( $self, ... ) = @_;

Hope this helps. Good luck!

P.s. you don't need to use EXPORTER for OO modules, as the methods are attached to the objects (rather than having to be imported into the caller's namespace).

In reply to Re: converting libraries into modules by rvosa
in thread converting libraries into modules by Andre_br

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.