in reply to Code Reuse

This follow up is just an example, and to be honest, I've put it here for thoroughness... it'll break in many cases, so don't use it.

You can exploit the symbol table to slurp in subs from modules that have imported them into their own namespaces. Know that "namespaces" are important in Perl (and in any other language that deals with them) due to logical (ie. lexical) scoping. The following will show how to check a 'use'd module for subs itself has, and import them all into the current namespace. Again, this is bound to break (I haven't even considered ramifications on included modules that use OO, and not using strict in the way I have here could be catastrophic (if it isn't already ;) ).

Rephrasing... it'll import *all* subroutines that's in the module's namespace as it currently sits, which is almost certainly not what you want. Look at it as indiscriminate inclusion.

First, the all-inclusive module you want to pull from (X.pm):

package X; use Data::Dumper; use File::Copy qw(copy); use Time::HiRes qw(usleep); 1;

Now, the x.pl script that wants everything from the module:

use warnings; use strict; use lib '.'; use X; BEGIN { no strict 'refs'; for (keys %X::){ my $symbol = "X::$_"; if (defined &{$symbol}){ print "importing '$symbol' sub into our namespace\n"; *$_ = \&{$symbol}; } } } print Dumper {a => 1}; usleep 500000; copy 'x.txt', 'y.txt' or die $!;

Output:

importing 'X::copy' sub into our own namespace importing 'X::usleep' sub into our own namespace importing 'X::Dumper' sub into our own namespace $VAR1 = { 'a' => 1 }; No such file or directory at x.pl line 20.

Please don't do this unless you know exactly why you're doing it, what you're doing it for, and with knowledge exactly why you want to 'cheat'. The other Monks have put forth much better examples of how to accomplish what you really want in much more eloquent ways.

This could be relatively trivially adapted so that the module itself saturates the caller script's namespace with the subs, but because this is not a recommended technique unless required for very specific purposes, I'll leave it up to the reader to figure that piece out.