Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
Object Oriented Perl - very basic guideby Preceptor (Deacon) |
on May 15, 2014 at 14:10 UTC ( [id://1086139]=perlmeditation: print w/replies, xml ) | Need Help?? |
I've been doing Perl for a while now, and one of the things I've meant to get to grips with, is 'object oriented' Perl. I think I'm getting there now, so I'm writing up what I've got so far in the hopes that it'll be a helpful reference. First, the basics - object oriented languages encapsulate code into 'objects'. The object has an internal state, and it's own 'code' for handling that state. The reason that's useful, is because if I write a module for you to use - then all you need to know is how to run the internal code, and don't have to worry about what goes on inside. That's why it's widely used in modules on CPAN, and chances are pretty good that you've already used it if you've used any CPAN modules. The way perl 'does' objects, is that it treats each object as a hash. The 'attributes' or 'internal state' are hash keys. As a start point (save as 'MyObject.pm')
You can then 'drive' this module with:
It's fairly simple, but what it means is that I can 'build in' all sorts of code and state variables into 'MyObject' - for example, validating when you 'set state' to ensure that it's not forcing something odd to happen. But this can happen transparently, and your code snippet doesn't actually need to worry about it. What you may not have seen before is the 'bless' keyword - when you create '$self' then you create a hash reference - which you could (and essentially, do) treat it as any other hash reference. What 'bless' does is 'mark' the reference as a specific type of object. So you'll see when you print '$object_instance' that it looks something like:
That's key, because it lets perl identify where it should look when you use a method - e.g. 'get_state' - it knows to look inside the 'MyObject' module explicitly.
is translated by perl (because it knows it's a 'MyObject' because of that 'bless') into:
(Passing $object_instance is necessary, because that has it's own internal state, and we need to know which internal state to modify). I wouldn't say it's something I'll always use as a technique, but it's a useful extra tool - if I've got a set of scripts that all do similar and related things, then there may well be value in creating a module for them to all use... and if you do, it's certainly worth considering using an object oriented module instead.
Back to
Meditations
|
|