asdf asdf - 4 months ago 14
Perl Question

Acces object created in another function

I have a main script, in this script I create a new object of another module, then I call a function from that module which creates another object of a second module.


use module::FirstModule qw ($hFirstModule);


use Exporter ();
@EXPORT = qw($hFirstModule);
use module::SecondModule qw ($hSecondModule);
sub new {
my $className = shift;
my $self = {key=>'val'};
bless $self, $classname;

return $self;
sub function{
#some other code here

I want to acces


Here is a very hacky approach that takes your updated code into consideration. It uses Sub::Override to grab the return value of the constructor call to your SecondModule thingy. This is something that you'd usually maybe do in a unit test, but not in production code. However, it should work. Here's an example.

package Foo;
# use Bar; # commented out because everything is in one file here

sub new {
    return bless {}, $_[0];

sub frobnicate {

package Bar;

sub new {
    return bless {}, $_[0];

sub drink {
    return 42;    # because.

package main;
# use Foo; # this will load Bar at compile time
use Sub::Override;

my $foo = Foo->new;

my $bar;          # this is lexical to the main script, so we can use it inside
my $orig = \&Bar::new;           # grab the original function
my $sub  = Sub::Override->new(
    "Bar::new" => sub {
        my $self = shift;

        # call the constructor of $hSecondModule, grab the RV and assign
        # it to our var from the main script
        $bar = $self->$orig(@_);
        return $bar;


# restore the original sub

# $bar is now assigend
print $bar->drink;

Again, I would not do this in production code.

Let's take a look at the main function. It first creates a new Foo object. Then it grabs a reference to the Bar::new function. We need that as the original, so we can call it to create the object. Then we use Sub::Override to temporarily replace the Bar::new with our sub that calls the original, but takes the return value (which is the object) and assigns it to our variable that's lexical to the main script. Then we return it.

This function will now be called when $foo->frobnicate calls Bar->new. After that call, $bar is populated in our main script. Then we restore Bar::new so we don't accidentally overwrite our $bar in case that gets called again from somewhere else.

Afterwards, we can use $bar.

Note that this is advanced. I'll say again that I would not use this kind of hack in production code. There is probably a better way to do what you want. There might be an x/y problem here and you need to better explain why you need to do this so we can find a less crazy solution.