in reply to Using a 'package' as a 'module', and choosing at runtime?

If I understand correctly, you want to have multiple modules together with the main script all in the same file. One way I can think of, without excessive rewrite, is by using a scalar reference to point to required package code at run-time, sort of a poor-man's dynamic link library.

#!/usr/bin/perl -w my $pkg; BEGIN { if ( $^O =~ /dar/ ) { $pkg = \&mac::get_answer } elsif ( $^O =~ /sol/ ) { $pkg = \&sun::get_answer } elsif ( $^O =~ /aix/ ) { $pkg = \&aix::get_answer } else { die "unknown os." } }; print "answer is " . &$pkg() . "\n"; exit 0; package mac; sub get_answer { return "Apple" } package sun; sub get_answer { return "Sun" } package aix; sub get_answer { return "IBM" } __END__

Replies are listed 'Best First'.
Re: Re: Using a 'package' as a 'module', and choosing at runtime?
by hardburn (Abbot) on Oct 28, 2003 at 16:32 UTC

    References to package subroutines are always done symbolically (even with strict 'refs' on), so you only need to change how the package is called.

    #!/usr/bin/perl -w my $pkg; BEGIN { if ( $^O =~ /dar/ ) { $pkg = 'mac' } elsif ( $^O =~ /sol/ ) { $pkg = 'sun' } elsif ( $^O =~ /aix/ ) { $pkg = 'aix' } else { die "unknown os." } }; print "answer is " . $pkg->get_answer() . "\n"; exit 0; package mac; sub get_answer { return "Apple" } package sun; sub get_answer { return "Sun" } package aix; sub get_answer { return "IBM" } __END__

    Which makes it a lot easier to add new class methods in the future.

    ----
    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

      Excellent! Thanks so much; this looks exactly like what I want to accomplish.