in reply to Common sub as method or function

You could also localize the sub you need into the main namespace:

local *main::timestamp = *Module::Base::timestamp;

It avoids exporting and still allows you to use just timestamp(). Be sure to document the localization though.

Replies are listed 'Best First'.
Re^2: Common sub as method or function
by clinton (Priest) on Aug 15, 2007 at 16:28 UTC
    It avoids exporting...

    It is still essentially exporting/importing, just without using Exporter.

    I completely agree with akho's recommendation to use Module::Base::Util, except that if we're only talking about two subs, it seems like overkill. (No doubt those two will become three, four, ten etc, so it is still probably the better way).

    My lazy tendency, however, would be, at this stage, to do as you have recommended.

    Clint

      I've reconsidered my answer, and I wonder if is there any functional difference between:

      local *main::timestamp = *Module::Base::timestamp;

      and:

      use Module::Base qw(timestamp);

      I think I would lean towards the latter being better practice. It is what I usually do, which makes me wonder why I came up with the local method first...

        use Module::Base qw(timestamp);

        is functionally equivalent to

        BEGIN { require Module::Base; Module::Base->import('timestamp'); }

        So it's at the very least wrapped in a BEGIN block (that is The Thing To Do when using your approach, anyway). It may actually do anything depending on how Module::Base::import was defined.

        It does what you mean when it was created by Exporter and timestamp is in @EXPORT_OK.

        Oh, and also: if you only want to import a sub into main::, you should not import the whole typeglob. Also, there is probably no need to import into main::timestamp is a rather generic name that may be used in some function/module you call, and things will soon get messy. Besides, local would be pretty much useless inside a BEGIN block (and that is very desirable). Use

        BEGIN { *Module::Derived::timestamp = \&Module::Base::timestamp; }

        or something.

        All this means that symbol table tricks should be severely incapsulated so that no living soul ever sees them Exporter.pm can help remove this mess!