I have a Perl script that creates an array of weak object references. When one of these objects goes out of scope, the reference to it in the array will become undefined.
ex (pseudo code):
# Imagine an array of weak references to objects my @array = ( $obj1_ref, $obj2_ref, $obj3_ref );
Is there a way to make an undefined link automatically be deleted from the array after it becomes undefined?
I want @array = ($obj1_red, $obj3_ref ) .
EDIT:
I tried this solution and it did not work:
#!/usr/bin/perl use strict; use warnings; { package Object; sub new { my $class = shift; bless({ @_ }, $class) } } { use Scalar::Util qw(weaken); use Data::Dumper; my $object = Object->new(); my $array; $array = sub { \@_ }->( grep defined, @$array ); { my $object = Object->new(); @$array = ('test1', $object, 'test3'); weaken($array->[1]); print Dumper($array); } print Dumper($array);
Output:
$VAR1 = [ 'test1', bless( {}, 'Object' ), 'test3' ]; $VAR1 = [ 'test1', undef, 'test3' ];
Undef is not automatically removed from the array.
Did I miss something?
EDIT 2:
I also tried removing undefined values from the array in the object's DESTROY method, but this also does not work. It seems that since the object is still not technically “destroyed”, weak references are still defined until the DESTROY method is complete ...
source share