in reply to Library file or module for sharing code?

If you use Exporter, you can get the best of both worlds by making the functions from Common available for import into your script:

COMMON 3

package Common; use warnings; use strict; use base 'Exporter'; our @EXPORT_OK=qw(get_uppercase); sub get_uppercase { my ($class, $name) = @_; return uc($name); } 1;

SCRIPT 3

#!/usr/bin/perl use warnings; use strict; use CGI::Carp qw(fatalsToBrowser); use Common qw(get_uppercase); my $name = "frodo"; $name = get_uppercase($name);

Update: Changed use Exporter to use base 'Exporter' to inherit properly. Sorry, bradcathey!

Replies are listed 'Best First'.
Re^2: Library file or module for sharing code?
by bradcathey (Prior) on Dec 28, 2005 at 13:23 UTC

    This looks exactly like the answer I was wanting, but I get this error:

    Undefined subroutine &main::get_uppercase called at /usr/www/users/foo +bar/cgi-bin/test.pl line 9.

    What is missing?

    Update: The only way I could get this to work was use all the code outlined in Simple Module Tutorial.

    package Common; use strict; use Exporter; use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); @ISA = qw(Exporter); @EXPORT = (); @EXPORT_OK = qw(get_uppercase); %EXPORT_TAGS = ( All => [qw(&get_uppercase)]); sub get_uppercase { my ($name) = @_; return uc($name); } 1;

    AND

    #!/usr/bin/perl -w use warnings; use strict; use CGI::Carp qw(fatalsToBrowser); use Common qw(:All); my $name = "frodo"; $name = get_uppercase($name);

    It needed:

    use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); @ISA = qw(Exporter); @EXPORT = ();

    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot

      The only important part that was missing was

      @ISA= qw(Exporter);

      But a better approach would be either:

      *import= \&Exporter::import;

      or, if you know you'll have a new enough version of Perl

      use Exporter qw(import);

      Because using inheritance to get a single method is a bad idea; it brings along too much unhelpful baggage.

      - tye        

        Thanks tye, went with:

        *import= \&Exporter::import;

        which worked fine (though I have no idea what is going on there--nothing in the docs I could find :)


        —Brad
        "The important work of moving the world forward does not wait to be done by perfect men." George Eliot
      Did you remember to include this line in your calling script?
      use Common qw(get_uppercase);
      @EXPORT_OK just says that it's "okay to export", but it doesn't actually do the exporting automatically. For that you'd want the @EXPORT array, though I don't necessarily recommend using it. Here's a good article on exporting. (Annoying pop-ups though.)