Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Moving from scripting to programming

by whittick (Acolyte)
on Oct 28, 2016 at 09:19 UTC ( #1174878=perlquestion: print w/replies, xml ) Need Help??

whittick has asked for the wisdom of the Perl Monks concerning the following question:

Firstly sorry for the ambiguous title. I have been using Perl for a good few years now, after having taught myself using 'Learning Perl'.

My question is, how do I move from by basic, procedural scripts to more of a fully fledged, object oriented approach?

When tasked with a problem I will follow the same format each time, using basic variables, arrays and functions. Yet when I find an existing solution to a problem the code is much more complex.

I guess what I'm asking is: Is there a recommended text to read after having completed the exercises in 'Learning Perl' that will take me to the next level (somewhere I could start thinking about applying for junior Perl dev roles)?


Replies are listed 'Best First'.
Re: Moving from scripting to programming
by BrowserUk (Patriarch) on Oct 28, 2016 at 09:55 UTC

    I'm going to express my opinion; plenty here will disagree with me. OO is not "better than procedural"; just different.

    Any programming problem can be solved equally well, or equally badly, using either OO or procedural -- or functional or declarative or any other programming paradigm -- code.

    Some tasks will lend themselves to the use of one paradigm over another; but an effective programmer in any general purpose programming language -- regardless of the (primary) paradigm it uses -- will be able to write an efficient and maintainable solution.

    Learning OO is a good thing for a programmer to do -- and so is a little functional experience, and some declarative etc. -- but do it for the right reasons; and do not expect it to be a passport to anything in particular.

    If you are an effective procedural programmer, and can demonstrate that, it should be enough to get you a job.

    Learning OO can improve your skills, if you are of the mindset and aptitude to see how and when to make use of it -- and when not. But if you do not have the aptitude for programming, it will not benefit you.

    Without hesitation I can say the 10 worst programs and the 20 worst programmers I've encountered in my career were all OO -- rigidly so -- and that was what made them bad.

    And I'll go one step further: any potential employer who won't employ you, simply because you don't have, or don't claim to have, OO programming experience, is not an employer you want to work for.

    Now please don't take this as saying you should learn to use OO programming; but do not see OO == "programming" and procedural/imperative == "scripting"; the difference between the two is at most a matter of scale; but mostly there is no difference at all. They are simply synonyms. With the use of the term 'scripting' generally being applied to programs written in dynamic, 'interpreted' languages; but otherwise an artificial distinction.

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Moving from scripting to programming
by Discipulus (Canon) on Oct 28, 2016 at 09:42 UTC
Re: Moving from scripting to programming
by davies (Prior) on Oct 28, 2016 at 10:11 UTC

    Are you using tests? If not, I suspect it's a better "next step" than OO, as it's more transferable. At the London Perl Workshop, I think last year, I attended a talk about code problems and one of them was using OO when it's actually harmful. The speaker gave some strong examples. But I've never heard of tests being decried.

    Likewise, are you using version control? If not git, then SVN or something else. Again, this is a transferable skill.

    If the project you are planning will be easier with OO, then please don't take this to indicate that you shouldn't.


    John Davies

Re: Moving from scripting to programming
by haukex (Archbishop) on Oct 28, 2016 at 12:05 UTC

    Hi whittick,

    I think the responses you've got so far are very good, I just wanted to throw out a few more thoughts on the matter.

    As for books, there's also Modern Perl. Once you've gotten through some of the Learning/Intermediate/Mastering Perl series, of course the Camel is great. A somewhat advanced book, but great if you want to "broaden your horizons" in regards to what's possible with Perl, is Higher-Order Perl.

    As others have said, I don't think OO is a requirement for "real" programs. There is a huge gray area between what might be understood as a "script" and a "real program" and that definition will differ from person to person. In addition to what was already mentioned by others, like testing and VCS, here are a few things that I think would move a script towards a program: try to avoid global variables, reduce repetition and refactor code into subroutines (that are hopefully re-usable; which can then be moved into your own modules and/or turned into OO methods), and use modules appropriate to the task instead of re-inventing the wheel.

    If you do want to go to OO, then probably the first thing I'd recommend is leaning how to do it in core Perl (e.g. perlootut and perlobj; Update: or Modern Perl's section Blessed References); I remember finding it quite eye-opening as to how in Perl, relatively little is needed to go from a simple hash reference to an object. If you want to code entirely in OO, then it's probably best to go to a framework like Moo or Moose.

    Hope this helps,
    -- Hauke D

Re: Moving from scripting to programming
by karlgoethebier (Abbot) on Oct 28, 2016 at 13:52 UTC
Re: Moving from scripting to programming
by eyepopslikeamosquito (Archbishop) on Oct 29, 2016 at 09:47 UTC

    Moving "from scripting to programming" is so much broader than whether to embrace a "fully fledged, object oriented approach"!

    Conway's Ten Essential Development Practices should help you appreciate that. For example:

    • Design the Module's Interface First. The most important aspect of any module is not how it implements the facilities it provides, but the way in which it provides those facilities in the first place.
    • Write the Test Cases Before the Code.
    • Use a Revision Control System.
    • Add New Test Cases Before you Start Debugging.
    • Don't Optimize Code -- Benchmark It.

    Modularity is a fundamental aspect of all successful large programs. In Perl therefore, modules are fundamental and you must master them. A study of top-rated CPAN modules is time well spent. For more details see: Writing Solid CPAN Modules.

    High-level Design Checklist

    • Know Architectural patterns. Choose wisely. Multitier archtecture is common.
    • Coupling and Cohesion. Systems should be designed as a set of cohesive modules as loosely coupled as is reasonably feasible.
    • Testability. Systems should be designed so that components can be easily tested in isolation.
    • Information hiding: Minimize the exposure of implementation details; provide stable interfaces to protect the remainder of the program from the details of the implementation (which are likely to change). Don't just provide full access to the data used in the implementation. Minimize the use of global data.
    • Interfaces matter. Once an interface becomes widely used, changing it becomes practically impossible (just about anything else can be fixed in a later release).
    • Design the module's interface first.
    • Design interfaces that are: consistent; easy to use correctly; hard to use incorrectly; easy to read, maintain and extend; clearly documented; appropriate to your audience. Be sufficient, not complete; it is easier to add a new feature than to remove a mis-feature.
    • Use descriptive, explanatory, consistent and regular names.
    • Correctness, simplicity and clarity come first. Avoid unnecessary cleverness. If you must rely on cleverness, encapsulate and comment it.
    • DRY (Don't repeat yourself).
    • Establish a rational error handling policy and follow it strictly.

    As for whether and when to use OO, there is no substitute for judgement and taste based on understanding and experience. A simple rule of thumb is to ask "do I need more than one?": if the answer is yes, an object is indicated; if the answer is no, then a module.

    For some general background on programming paradigms, I quite like Stroustrup's description of different programming styles in C++, a multi-paradigm programming language:

    • Procedural: Decide which procedures you want; use the best algorithms you can find.
    • Modular: Decide which modules you want; partition the program so that data is hidden within modules.
    • Data Abstraction: Decide which types you want; provide a full set of operations for each type.
    • Object Oriented: Decide which classes you want; provide a full set of operations for each class; make commonality explicit by using inheritance.
    • Generic: Decide which algorithms you want; parameterize them so that they work for a variety of suitable types and data structures.
    Though Perl is also a multi-paradigm language, it has significant differences from C++ -- for example, Perl is dynamically typed while C++ is statically typed -- so a Perl design of a given system may vary significantly from a C++ one.

    See also:

    Updated 2020: Minor changes to "High-level Design Checklist" section.

Re: Moving from scripting to programming
by stevieb (Canon) on Oct 28, 2016 at 13:03 UTC

    Excellent answers so far, I especially liked the recommendations for learning about unit testing.

    I wouldn't say that object oriented is more advanced than functional, it's just a different way to do something. The biggest benefit I get from OO is the ability to keep state, as well as being able to include objects within other objects and the ability to pass objects around as other function/method (a method is a function that is called through an object or a class) parameters.

    Although there have been great recommendations so far, I like to plug Learning Perl Objects, References and Modules by Randal Schwartz whenever I can (more for the references part, but if you want to advance, mastering references is a very good place to start, as that's what an object is anyway). This book covers a few topics that will get you going forward.

      IMO, there doesn't need to be a sharp distinction between the two.

      I've got a scheme I've been using in which everything is contained in a $universe hashref, which contains a set of game objects, which themselves contain plenty of hashrefs and/or arrayrefs for sub-objects as applicable.

      Very conveniently, the entire state can be saved and reloaded as a basic vanilla data structure with Storable.

      It is object oriented in the sense that each module of the project deals with a certain strata of the universe tree and each element in that layer is best thought of as an object. But the code is given the objects instead of the objects having the code.

      There are few safety rails with this setup, and a bit of crossover between objects, but a little self control goes a long way and the freedom is wonderful when you don't have to deal with other people :).

        Very good points you've made.

        "IMO, there doesn't need to be a sharp distinction between the two."

        Agreed, and in fact, in certain modules I've written, I provide a new() function that returns a standard blessed-hash object and the other functions then become methods, but internally it's an illusion, as there's no ties to OO at all, and the functions can be exported as well for those who prefer functional (this is a module that wraps a C library, so I wanted a user to be able to use it in the same way they would the real library, or Perl OO if they chose:


        sub lcd_home { shift if @_ == 2; lcdHome($_[0]); } sub lcd_clear { shift if @_ == 2; lcdClear($_[0]); } sub lcd_display { shift if @_ == 3; my ($fd, $state) = @_; lcdDisplay($fd, $state); }

        That effectively wipes out a class or object. No param checking as I just pass that off to the C library which already takes care of that. The same module also exports the C function calls in their original naming convention (camelCase) if desired alongside the more perlish snake_case. A functional module that also acts OO-ish. Perl: TMTOWTDI ;)

Re: Moving from scripting to programming
by haukex (Archbishop) on Oct 28, 2016 at 14:04 UTC

    Hi whittick,

    Another idea: you could post a short (say, 100 lines) script whose style you think best represents your coding so far, and I'm sure one or two monks (possibly including myself, as time allows) might have some tips as to which direction to go in your further reading.

    -- Hauke D

Re: Moving from scripting to programming
by BillKSmith (Monsignor) on Oct 28, 2016 at 13:31 UTC
    I would recommend the book "Perl Cookbook" ISBN 9780596003135. Rather than teaching details of Perl, it teaches how to apply Perl to common problems. You will often use its solutions "as is", but more important is the insight in how to use Perl effectively on your own problems.

      ++ for this. I only had the original edition but just last week picked up a pristine used copy of 2nd ed. on Amazon for eight bucks!

      The way forward always starts with a minimal test.
Re: Moving from scripting to programming
by eyepopslikeamosquito (Archbishop) on Oct 29, 2016 at 09:31 UTC
Re: Moving from scripting to programming
by Phenomanan (Monk) on Oct 28, 2016 at 13:12 UTC

    Assuming you already have experience with object-oriented programming in other languages, this page should help out. Books were very helpful for getting me started on Perl, but I think (at least for me) it can also be beneficial to look things up online as I need them and find examples.

    However, if you do not have any prior experience with object-oriented coding, I would then definitely suggest hitting the books first. I'm sure all the suggestions on this thread are a good place to start. You can also look through the review section of this site to find more books.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1174878]
Approved by Athanasius
Front-paged by Arunbear
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2023-11-28 14:40 GMT
Find Nodes?
    Voting Booth?

    No recent polls found