Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

A simple example OO script for total beginners

by bl0rf (Pilgrim)
on Sep 05, 2003 at 01:11 UTC ( [id://289076]=perltutorial: 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

Replies are listed 'Best First'.
(counter-intuitive) Re: a simple example OO script
by Anonymous Monk on Sep 05, 2003 at 09:16 UTC

    If I were a total beginner and I needed to know how to create an object, after this example I would be able to go through my first module.

    However, if I were a total beginner, I would be also totally ignorant about objects and what they are.

    More specifically, if I were a total beginner, I would be used to work with numbers in this way:

    $n = 7; $n = $n + 3; # or if I am less than a beginner $n += 3; # $n = $n - 5; $n = 99999;

    Therefore I would be more than puzzled with your example that changes my way of dealing with numbers from $n += 3 to $obj->add(3) without any visible benefit for this additional burden.

    So, if I were a total beginner, from your example I would probably learn what to do, but not why.

    What I am getting at is that Object Oriented programming is supposed to make things easier for the programmer, not more difficult. The purpose of OOP is to imitate reality. That's why there are objects. SO your example would have been more attractive if you were talking about something we can see and touch, such as cars or books.

    There are some better examples available in the Monastery. Have a look at our Tutorials section.

    Also, your example would look much bettere if it was properly formatted. Consider using perltidy, or some smart editor.

Re: A simple example OO script for total beginners
by ajdelore (Pilgrim) on Sep 05, 2003 at 15:48 UTC
    1; # this 1; is neccessary for our class to work

    Although this is true, I think that it would be more instructive to indicate what the 1; statement does, and why it is neccessary for the package to work.

    The module has to return something to indicate success ie. a non-zero/null value. Someone new to the language might not know that by default perl will return the value of last statement. Perhaps you should use an explicit return statement, something like:

    return 1; # let program know package has successfully compiled

    Rather than just mentioning that there are other tutorials available, it would also be useful to link to some of them from this post.


      The module has to return something to indicate success

      I'd like to clarify. This is indeed not necessary for the class to work, but for perl to assume the inclusion of a file went well. When you do, use or require a file containing perl code, the value it returns to the caller is used to indicate proper loading, execution, or whatever the role of that code was. It is customary to end any perl code, especially that which is not a script pe se in a simple


      because this is not erroneous as using return is when there's nothing to return to (like in a simple script file), but does return truth when truth is needed, because in Perl the last value evaluated in some scope which returns (file, subroutine), is the return value.

      In short, it's not necessary for the class to work, but it is necessary if the module which contains the class will be loaded via an external file inclusion, instead of being supplied in the same file.

      zz zZ Z Z #!perl
      An excellent article which got me started with OOP in Perl. This is exactly the kind of thing I was looking for.
      However, I would like to point out something. The
      at the end is not entirely necessary. We can just as well use,
      our @ISA=qw/Exporter/;
      Which I guess is a better way of telling the world, that you may import this package/class in your own scripts.
Re: A simple example OO script for total beginners
by mikasue (Friar) on Apr 12, 2006 at 21:33 UTC
    Hi. I'm new to Perl and perlmonks but not to programming. I know C++ very well and understand all the logic and code behind OOP in C++. I am writing a program in Perl and found that I need to use some OOP concepts but didnt' know where to start in Perl. This tutorial really helped. Knowing the concept behind OOP and knowing how to do it in C++ really helped. Your comments in the code helped also.
Re: A simple example OO script for total beginners
by perloHolic() (Beadle) on Jan 08, 2015 at 17:00 UTC
    It may be over a decade since this turorials' creation, however, I come back to this tutorial often to recap as I am farmiliar with OO in C and Java but not necessarily OO Perl - and since I have only recently become a monk, I thought it high time to actaully praise this link as opposed to just reading it all the time! Thanks bl0rf!
Re: A simple example OO script for total beginners
by bl0rf (Pilgrim) on Sep 06, 2003 at 00:39 UTC
    Thank you for your feedback, all of you are totally right, but this is the first tutorial
    that I have ever written and I was planning on it being very
    minimalistic and not try to bite off more than I can chew ( explain all the details ).
    I would have edited my post have I had editing privileges :-).
Re: A simple example OO script for total beginners
by PhosphoricX (Sexton) on Oct 27, 2005 at 16:51 UTC
    I think there is a typo on line 49 of your example:

    return self->{num};

    should be

    return $self->{num};
Re: A simple example OO script for total beginners
by chanio (Priest) on Aug 03, 2005 at 04:14 UTC
Re: A simple example OO script for total beginners
by spx2 (Deacon) on Dec 29, 2007 at 12:53 UTC
    I suggest you look into Moose. it's a very nice OOP framework
      Cool, thanks for the Moose!
Re: A simple example OO script for total beginners
by devslashneil (Friar) on Sep 05, 2003 at 06:43 UTC
    A very interesting article thanks a lot, it was exactlly what i needed to point me on the right track with OOPerl :)

    Neil Archibald
    - /dev/IT -
Re: A simple example OO script for total beginners
by Anonymous Monk on Oct 13, 2005 at 11:28 UTC
    Really good job... I was a real beginner and it was very usefull for me and thru the example i got answers for lots of questions in my mind. thanks,
Re: A simple example OO script for total beginners
by Anonymous Monk on Nov 29, 2005 at 21:26 UTC
    Your no-nonsense tutorial on Perl OO was helpful, I feel less intimated to start writing in non-procedural Perl code for things which require special consideration. Thank you :-)
Re: A simple example OO script for total beginners
by Anonymous Monk on Jan 05, 2011 at 20:24 UTC
    Thanks for the tutorial, you filled in the blanks, that all the other tutorials left out!
Re: A simple example OO script for total beginners
by Anonymous Monk on Feb 07, 2014 at 05:35 UTC
    Great Article ..

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perltutorial [id://289076]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-04-24 03:47 GMT
Find Nodes?
    Voting Booth?

    No recent polls found