Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Object Oriented Perl examples for OO beginners

I love Perl but its object-oriented facilities are downright screwy.
I was afraid to touch OO with a ten foot pole until I learned
how to use it from a C++ book ( yes, I am multilingual ). So
as a result I could do OO in C++ but I was still scared of it in

A week ago or so, I took out the book "Programming The Perl
DBI" from my local library. It had a very simple object-oriented
script that encouraged me to start experiencing Perl OO.
I wrote my first object-oriented module and I'd like to
share it with you. I strongly recommend that you read the OO documentation
that comes with perl ( perltoot, perlobj ) before looking at the example
scripts, but since the examples are only useful for OO novices I will
try to comment the code as best as I can.

My own Object Oriented Perl module

#!/usr/bin/perl #, a number as an object package Number; # This is the "Class" sub new # constructor, this method makes an object # that belongs to class Number { my $class = shift; # $_[0] contains the class name my $number = shift; # $_[1] contains the value of our number # it is given by the user as an argument my $self = {}; # the internal structure we'll use to represent # the data in our class is a hash reference bless( $self, $class ); # make $self an object of class $class $self->{num} = $number; # give $self->{num} the supplied value # $self->{num} is our internal number return $self; # a constructor always returns an blessed() # object } sub add # add a number to our object's number { my $self = shift; # $_[0] now contains the object on which the meth +od # was called (executed on) my $add = shift; # number to add to our number $self->{num} += $add; # add return $self->{num}; # by returning our new number after each operation we could see # its value easily, or we could use the dump() method which could # show us the number without modifying its value. } sub subtract # subtract from our number { my $self = shift; # our object's internal data structure, as above my $sub = shift; $self->{num} -= $sub; return $self->{num}; } sub change # assign new value to our number { my $self = shift; my $newnum = shift; $self->{num} = $newnum; return self->{num}; } sub dump # return our number { my $self = shift; return $self->{num}; } 1; # this 1; is neccessary for our class to work
A method ( all the subroutines in the script ) is a command that you can execute on an object. It acts on the object's internal data, which in this case is represented as a hash. $self = {}; $self is passed to bless() and it must be a reference to whatever internal data structure we're using, it could be an array $self = []; or a scalar reference.

Using the Object Oriented module

Having the Number module is fine and dandy but if you cant use it than...its useless.
Here is a little script that uses
#!/usr/bin/perl # using the Number module use Number; $obj = Number->new(7); # call the constructor w/a value # $obj now contains our object from before. remember # that new() returned it ( in the guise of $self ) print "the number is ",$obj->dump(),"\n"; $obj->add(3); # call the add() method on our object print "now the number is ",$obj->dump(),"\n"; $num = $obj->subtract(5); print "now the number is $num\n"; # remember that subtract() returns the current value of our number # so that $num has that value assigned to it. $obj->change(999999); print "number changed to ",$obj->dump(),"\n"; # NOTE: if you include the object method inside the double # quoted string in print() then it wouldnt work, it'll return the # memory address of the object and "->dump()" appended # to it... exit();
This script works on the assumption that ( the file
containing our class, our module ) is either in the perl module
directory or is in the same directory as itself. To load a module
from somewhere else take a look at the @INC array in perlvar.

The output of the script that uses is this:
the number is 7
now the number is 10
now the number is 5
number changed to 999999

To see this for yourself just type "perl" at the prompt, paste the code
for and then the code for right after it onto the same
screen ( this is called interactive-mode ). When your'e done just press the
key combination Control-D and the code will execute. An interesting thing
to remember is that doesn't always need its own file, you
can have and in the same file provided that you
write the line "package Number;".

Whew, that was fairly long. If you dont understand what my
scripts do dont despair, copy them and run them, or read some
OO Perl tutorials. If youre completely stumped then try tackling
OO in C++ since it has a nicer interface to object-orientation
than Perl. Perl is still the greatest though...

- Jacob F

In reply to A simple example OO script for total beginners by bl0rf

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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    [choroba]: why do you need to access metacpan via http?
    [usemodperl]: stop asking why, just say how
    usemodperl pulls teeth...
    [usemodperl]: change the world? you mean BREAK THE WEB? we will regret this once google starts pulling certs for cursing or something...
    Veltro Sees open mouth and feeds troll
    [Corion]: usemodperl: Naah, you're just being unreasonable. It's not hard to download https URLs, and we've shown you ways to avoid downloading at all, and ways to keep downloading via http possible. You reject both.
    [choroba]: Also, try asking at IRC
    [usemodperl]: corion baby you have done nothing of the sort
    [usemodperl]: asking how to download from cpan with core perl via http is unreasonable???
    [Corion]: usemodperl: No, asking is not unreasonable. Insisting that it must always keep working for you is unreasonable.

    How do I use this? | Other CB clients
    Other Users?
    Others perusing the Monastery: (10)
    As of 2018-06-24 16:33 GMT
    Find Nodes?
      Voting Booth?
      Should cpanminus be part of the standard Perl release?

      Results (126 votes). Check out past polls.