Is there an advantage to storing the large object as a reference to the large object instead of the object itself?
An object in Perl is just an anonymous data structure (it just happens to be blessed) that is referred to by one or more references, so in code that uses the object you'd never really store "the object itself" in a variable, but only a reference. You are free to take as many references to the same object as you like*, but in regards to "storing the object itself", I don't understand the question, and I think a Short, Self-Contained, Correct Example would help.
* However, if you have your "one big object" storing references to your "smaller objects", and your smaller objects referring back to the big one, you've created circular references that will prevent the objects from being garbage-collected, in other words, your program has a memory leak. One way to deal with this is to weaken one of the references on one end with weaken from Scalar::Util. Note that even code like you showed in the reply here will still mean there are circular references.
In the following code, try commenting out the line weaken($self->{big_obj}); and see how the output changes to show the memory leak.
use warnings; use strict; { package Big; sub new { my $class = shift; bless {@_}, $class } sub new_little { my ($self,$id) = @_; push @{$self->{little_objs}}, Little->new(id=>$id, big_obj=>$self); return $self; } sub DESTROY { print "DESTROY ",__PACKAGE__," id=",shift->{id},"\n" } } { package Little; use Scalar::Util qw/weaken/; sub new { my $class = shift; my $self = {@_}; weaken($self->{big_obj}); return bless $self, $class; } sub DESTROY { print "DESTROY ",__PACKAGE__," id=",shift->{id},"\n" } } my $big1 = Big->new(id=>"One")->new_little("Hello"); print "Clearing \$big1...\n"; $big1 = undef; # no more references to object should cause GC my $big2 = Big->new(id=>"Two")->new_little("World"); print "Clearing \$big2...\n"; $big2 = undef; END { print "END\n" }
Minor edits for clarity.
In reply to Re: Is there an advantage to storing references to objects in an attribute instead of the object itself?
by haukex
in thread Is there an advantage to storing references to objects in an attribute instead of the object itself?
by nysus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |