leocharre has asked for the wisdom of the Perl Monks concerning the following question:

I've asked this before but I think I'm having a hard time being clear. Or this is somehow beyond my head. I have a subroutine that I want to define in module Fruit.pm. Fruit.pm exports this sub first to the main calling program, makesalad.cgi.
Fruit.pm also calls

i have Fruit.pm, Apple.pm, makesalad.cgi

package Fruit; use vars qw{$VERSION @ISA @EXPORT @EXPORT_OK}; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(slice slice_some); use strict; sub slice; # so i don't have to call slice() - is this the right place + to do this ? sub slice_some; sub slice_some { slice 'grapefruit'; slice 'straberries'; } sub slice { my $thing = $_[0]; defined $thing or $thing = 'default_thing'; # slice here.. } 1;
package Fruit::Apple; use vars qw{$VERSION @ISA @EXPORT @EXPORT_OK}; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(cut); use strict; use Fruit; sub cut; sub cut { my $thing = $_[0]; defined $thing or $thing = 'default_thing'; # cut here.. and then also use slice... slice 'mango'; slice; } 1;
#!/usr/bin/perl -Tw # this is makesalad.cgi use strict; use Fruit; use Fruit::Apple; slice_some; slice 'orange'; slice; cut; exit;

the subroutine slice is being accessed by all three parts of the program- but the subroutine slice is only accessible to makesalad.cgi and Fruit.cgi, not to Apple.cgi even though it also makes use of Fruit.pm.. The only way to call slice properly in Apple.pm is to do this : ::slice(); - why?? Is it because *use* only runs once therefore slice is only accessible to main? What is going on here? is it because use is a one time pre compile thing, should I use require for Fruit.pm on both makesalad.cgi and Apple.pm ? Ouch.. Help .. ouch..

Replies are listed 'Best First'.
Re: making a subroutine export into the main script and also to other modules
by chromatic (Archbishop) on Mar 20, 2006 at 02:52 UTC

    use has two parts. The first, the require part, loads the named module, unless perl has already loaded it. The second part calls the module's import() method, which usually exports symbols into the calling package's namespace. That second part always happens, even if perl has already loaded the call and regardless of how many other modules have called that import().

    I recommend using use Module; in all code that needs to use Module's code. It's nicely self-documenting that way, plus if you ever use that module from outside of your program (and without other code that actually uses the Module on which your code relies), you don't have to worry about mysterious failures when it's not there.

      Actually what I am having to do is make a 3rd module, then it works fine. I think it has something to do with the fact that the 3rd module is in Fruit::Common ?