perl.j has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to build in a subroutine that YOU made into YOUR computer without always rewriting the subroutine or copying and paste it.

Replies are listed 'Best First'.
Re: Building in a Subroutine?
by jethro (Monsignor) on Jul 08, 2011 at 16:15 UTC

    Yes, we call that a module. For example if I have a file functions.pm like this:

    package functions; use strict; sub printsomething { print "hello\n"; } 1;

    I could use that subroutine in my script like this:

    #!/usr/bin/perl use functions; functions::printsomething();

    Naturally this isn't all, you can include the module even when it is not in the same directory as your script. Or include it so that you can just use printsomething() instead of functions::printsomething() (by using another module called Exporter in your module).

    You can read about modules in one of the perl tutorials or in the reference section perlmod

Re: Building in a Subroutine?
by davido (Cardinal) on Jul 08, 2011 at 16:47 UTC

    The Perl POD is a little "head first" with respect to introducing modules. perlmod is not a tutorial. This is where a book like Intermediate Perl (Published by O'Reilly) is very helpful. It will walk you through the basics of modules, and then take you into more advanced topics such as putting together a module distribution (tests and all).

    But the basic idea is that you create a module in its own file. It has its own namespace. You can choose to export some of its functions into the caller's namespace, or make exporting optional. You can write a functional interface, or an object oriented interface, or a combination of both. Within the calling script, you use ModuleName;, along with an import list if necessary. Then within the calling script, you can use those functions (or classes/objects) without copying and pasting every time you want their functionality.

    there are lightweight techniques too, but they're rarely used nowadays in well-written code; techniques such as reading in a file of code and evaling it, or do Fildname;, and others. But in this day and age, such techniques are not really considered suitable 99.9% of the time. I mention them only because they show up in older code from time to time, and you may see them.

    Grab a copy of Intermediate Perl at your favorite bookstore. If you intend to become effective in using Perl, it's $20 dollars well spent.


    Dave

      I am currently reading the book Learning Perl. I, unfortunately, just found out it is in this book's 6th edition. Just a little though. Thank you to everybody.

Re: Building in a Subroutine?
by Anonymous Monk on Jul 08, 2011 at 15:59 UTC

    Not sure what you mean. Perhaps you want to put your code into "mystuff.pm" and then use mystuff; in other scripts?

      I think that is what I am looking for. Thank you.

Re: Building in a Subroutine?
by Anonymous Monk on Jul 09, 2011 at 03:19 UTC