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

Hi all,
I am just getting into using Perl objects. When I want to use my objects across files (and packages), the only way I have found to do so is to pass the reference to the object:
# File1 use ObjectMaker; # ObjectMaker has all the exporter stuff use Foo; my $Object = ObjectMaker->new(); &Foo::DoSomething(foo, bar, \$Object);
But I thought new() returned a reference? So the way I have been accessing my objects in the other files is
# File 2 package Foo; use ObjectMaker; sub DoSomething { my $foo = shift; my $bar = shift; my $Object = shift; ... my $blub = $$Object->MethodName(blah); } 1;
Is there a more accepted way of doing this or am I on the right track?

Thanks for any enlightment from this august body,

Bob C.

Replies are listed 'Best First'.
Re: Using Objects across files and packages
by itub (Priest) on May 06, 2004 at 21:46 UTC

    Indeed, object constructors return a reference. In general, you should just use that reference without further indirection.

    my $Object = ObjectMaker->new(); Foo::DoSomething(foo, bar, $Object); $Object->MethodName(blah);

    You only need to do Foo::DoSomething(foo, bar, \$Object); in the very uncommon case where you want DoSomething to be able to change where your reference ($Object) points to.

    Updated to be add more details: for example,

    DoSomething(foo, bar, \$Object); print $Object; # prints "42" sub DoSomething { my $foo = shift; my $bar = shift; my $Object = shift; $$Object = 42; }

    Now the caller will notice that his $Object is not longer an object reference but a scalar with value 42! This way of passing parameters by reference so that they can be modified is very common in C and Fortran, but not so common in Perl

Re: Using Objects across files and packages
by NetWallah (Canon) on May 06, 2004 at 21:59 UTC
    I think the confusion is in the interpretation of this line:
    my $blub = $$Object->MethodName(blah);
    The -> operator already does a dereference.
    The extra "$" would cause a double-dereference, so it should not be used.

    Offense, like beauty, is in the eye of the beholder, and a fantasy.
    By guaranteeing freedom of expression, the First Amendment also guarntees offense.