In past Meditations and Wisdom Queries I have complained that I don't use Perl enough to remember it. Knowing this I over comment and tend to have 1000s of code parts laying about my ~/code directory.

I have begun to think that perhaps I should (careful now I have an English degree, please do not try this at home) Teplatize my Perl scripts. I do a lot of log reading, data converging and file creation, or, basically the same things over and over with Perl. As a result I am constantly cutting and pasting old code, not just because I am lazy but because I literally cannot remember how to do what I did last time.

I would use these templates later to build the scripts I need to write now and again. Sort of a personal Perl Cookbook. Like stepping though a file and doing this or that to every entry. Transliterating this for that. Opening and closing files and that sort of thing.

What would you folks "save" to remember later? What do you think is important to Templatize?
There's more than one way to do it, but only some of them actually work.

Replies are listed 'Best First'.
Re: Perl Templates
by flyingmoose (Priest) on Feb 10, 2004 at 16:52 UTC
    The number 1 virtue of a programmer is laziness. Yes, so the Wall speaketh, but really...he makes a good point.

    Start motivating yourself by reminding yourself that cut and paste is annoying, slow, and you forget where things should be copied from. Then, write lots of modules, and reuse them. Don't bother cutting and pasting any more, you won't have to!

    I'd start by trying to sort your modules out by what they do, and then naming the modules appropriately. Perl has a ton of built in documentation on the subject, and a few monks with better memories than I can probably direct you to the "perldoc" functions on making and using modules. One such document is "perldoc perlmod", but it's not exactly the most intuitive documentation out there.

    Templatizing code to accelerate copy-and-paste ability is anti-design, IMHO. It can lead to maintaince problems as well, but more importantly, it keeps one from learning how to perform certain operations without aid of documentation -- and it keeps one from thinking in the realm of new/innovative software design.

Re: Perl Templates
by artist (Parson) on Feb 10, 2004 at 15:55 UTC
    Write your own modules.Build your libaries. That is what code re-use all about it.

    If you really have problems with opening/closing files, you need little practice. May be your mind is faster on 'what' part rather than 'how' part. But there is some Perl which is essential and you should atleast read "Learning Perl" or any other basic Perl book as a refresher.

    You can write all your essential code in one script use that as a template if you think template is way to go.


Re: Perl Templates
by valdez (Monsignor) on Feb 10, 2004 at 15:53 UTC

    Have you considered transforming those snippets in modules? After many reuses of a snippet it should be natural to transform it in something reusable... isn't it? Haven't you find anything interesting on CPAN?

    Ciao, Valerio

Re: Perl Templates
by Abigail-II (Bishop) on Feb 10, 2004 at 15:52 UTC
    This is an open door, right? People have been writing modules and libraries decades before Larry released Perl 1. It's called "code reuse", and I wouldn't be surprised if even Lady Lovelace did that.


      This is why I keep telling people I'm NOT a programmer.

      There's more than one way to do it, but only some of them actually work.
        Some other posts suggest writing modules, which is the normal thing for programmers to do. But as you are
        "NOT a programmer" :-)
        perhaps the more old-fashioned use of files that contain subroutines for you to reuse would be easier to implement?

        For example, in your brand new program that does the day's latest challenge (and perhaps you start with a virtual template of a script that you know functions vaguely similarly) you have something like:

        require ''; my $var1 = shift; my ( $var2 ) = mgs::get_data( $var1 );

        Then, in a file named that is in one of the @INC directories (thus allowing to be in the current directory), you start with:

        package mgs;

        followed by subroutine after subroutine (i.e. no "main" stuff required in this library file, just cool subs that you want to reuse and maybe some initializing statements). Eventually, the file even contains the subroutine you are invoking as in:

        sub get_data { my ( $name, # optional comment explaining @name $grade, # optional comment for optional $grade ) = @_; my $answer; # Do stuff with $name, $grade, concoct some kind of $answer # ... return ( $answer ); }

        Keeping to the general rule of one package statement per library file (i.e. files like '' as above), you create several of these library files to contain related subroutines. Suddenly, code reuse becomes a piece of cake! (Check out how to pass filehandles as parameters and also ways of redirecting STDERR to always point to the same file for more robustness here.)

        As you are alluding, it's great to write code just once so that you aren't always rewriting the same old thing (also multiple-script maintenance is easier), but since Perl code is fairly easy to generate anew as necessary, you get the best of code reuse without being locked into a one-template-fits-all approach.

Re: Perl Templates
by leriksen (Curate) on Feb 11, 2004 at 00:21 UTC
    Some important lesson you can absorb before starting is

    'Plan to write your library twice, you will anyway'

    which means, because you aren't really sure what you want, or how to do it properly, your first attempt will be OK, but you'll soon wish you had done it differently. Dont worry, do it again, using the lessons AND experience you now have.

    'Try to write the interface in a way you think wont need to change'

    Hard to do, especially if this is your first attempt. Generalise what you are trying to do. Dont write a 'calculate_fuel_tax()' function or method. Perhaps an 'apply_tax(tax_type)' method is more general, with the _implementation_ doing the gritty work for each tax type.

    'Write test cases for EVERYTHING in your library'

    In short, if you decide at some point to replace the guts of a method (or entire library), a regression test suite gives you a lot of confidence your dependent code and libraries will still work. Its like replacing your car engine from petrol to electric - as long as all the controls still work the same way, you can drive it exactly the same way.
    Use the excellent Test::More and ExtUtils::MakeMaker modules - learn to use them very well, it is well worth the effort - study existing CPAN modules for how they use them

    A technical suggestion

    'Use hashes as your parameters to methods/functions'

    The code becomes self documenting, and more mnemonic. Which is easier to understand and remember

    my $result = apply_tax(type => 'fuel', state => 'CA', period_start => '01/02/2004', period_end => '12/02/2004');
    my $result = apply_tax('fuel', 'CA', '01/02/2004', '12/02/2004');

    use warnings;use strict;use brain;

      'Plan to write your library twice, you will anyway'
      I read this as a citation from "The Mythical Manmonth". The newer edition of this book contains a comment on this idea stating that in fact you need to take into account constant refactoring and sometimes rewriting not necesserilly exactly twice.
Re [0]: Perl Templates
by Intrepid (Deacon) on Feb 10, 2004 at 21:52 UTC

    Hello. The distinction between library (module) code and script code is important to my answer. I am now using scriptdist and a Vim (my Vi Improved editor) template to automate repetitive coding in my scripts. This is as much templating as I feel I need right now, and it is helping a lot.

    If you wonder what is in the Vim template, it is the basic stuff like the perlstarter ("shebang") line and "use strict;" and so on. The scriptdist tool provides supporting files like a MANIFEST and all that (Makefile.PL notably) so that my naked scripts can become installable packages.

    scriptdist is perl software by brian d foy and can be found on CPAN


        Soren A / somian / perlspinr / Intrepid
    P.S. Don't forget: I am expecting all the people the people who say I am posting to Perlmonks for the XP to automatically downvote this posting w/o explanation, thanks.

    Cynicism is not "cool" or "hip" or "intelligent". It's like Saddam Hussein's piss mixed
    with 004 grit and nitric acid. It's corrosive to everything it touches, destructive to
    human endeavors, foul and disgusting. And ultimately will eat away the insides of the
    person who nurtures it.
Re: Perl Templates
by kutsu (Priest) on Feb 10, 2004 at 19:21 UTC

    Personally I prefer templates for html only, esp. for creating web based printable reports. For perl code I prefer modules, the monestary happens to have a nice tutorial on this.

    "Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce