The basics are easy enough. Say you want to make a module named My::Foo. You put a package My::Foo; at the top of the module file to declare what package it is in. After that, you put all your subroutines you want in that file. Modules need to return a true value to indicate that they were loaded successfuly, so you put a 1; at the very end of the file. It is common to put an __END__ declaration after that, but not required.

To access the module, you need to place it in some directory specified in the @INC global array. Since the module is named My::Foo, which uses the :: sperator, we need to place our module in the correct subdirectory under some @INC dir. The :: seperates the directory path, so we place the module under My/Foo.pm (note the .pm extention, which all Perl modules have).

There are a few ways to call your subroutines. For all of them, you have to put a use My::Foo; before you call any of them. Then you could call a subroutine named bar() like this:

My::Foo->bar(); # 'My::Foo' will be the first param passed My::Foo::bar(); # doesn't touch the param list

You can also use the Exporter module to call bar() without specifiying the full module--see the documentation for Exporter.pm.

That's the quick-and-dirty overview, which glosses over a lot of cool stuff.

----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer

Note: All code is untested, unless otherwise stated


In reply to Re: routines as separate files? by hardburn
in thread routines as separate files? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.