in reply to Agile syntax (abuse?)

This seems to work for me.

use strict; END { print "END\n" }; { package SubRef; use Scalar::Util qw(weaken refaddr); sub DESTROY { my $self = shift; print "DESTROY ".ref($self) ."\n" +} sub new { my $class = shift; my $copy; my $self = $copy = bless(sub { $copy->ok }, $class); weaken $copy; return $self; } sub ok { print "SubRef ok ".refaddr($_[0])."\n" } } { package ArrayRef; @ArrayRef::ISA = qw(SubRef); sub new { my $class = shift; return bless [], $class; } } { package CircularRef; @CircularRef::ISA = qw(SubRef); sub new { my $class = shift; my $s = {}; $s->{self} = $s; return bless $s, $class; } } for (1..2) { my $sub = SubRef->new; my $sub2 = SubRef->new; my $arr = ArrayRef->new; my $cir = CircularRef->new; $sub->(); $sub2->(); } print "After For\n";


It prints the following:

paul@paul-laptop:~$ perl foo SubRef ok 135976352 SubRef ok 135976436 DESTROY ArrayRef DESTROY SubRef DESTROY SubRef SubRef ok 135976352 SubRef ok 135976424 DESTROY ArrayRef DESTROY SubRef DESTROY SubRef After For END DESTROY CircularRef DESTROY CircularRef


I was having issues getting it to work - but then I moved from a one-liner to a program and suddenly the world was fine. I think that the similar action in new would work on your calls also.

Update - Just to double check I used the following lvalue based subref which worked also.

my $self = $copy = bless(sub :lvalue { $copy->ok; my $n }, $cla +ss);


my @a=qw(random brilliant braindead); print $a[rand(@a)];

Replies are listed 'Best First'.
Re^2: Agile syntax (abuse?)
by blazar (Canon) on Apr 04, 2007 at 11:08 UTC
    I was having issues getting it to work - but then I moved from a one-liner to a program and suddenly the world was fine. I think that the similar action in new would work on your calls also.

    Thank you: in view of the other answers the problem is not so much of a problem any more. Yet I was annoyed by not being able to use weaken appropriately, and you gave me an explicit example about how to put it to work. Thinking of your actual example code, anyway, makes me think that while weaken() is a precious tool, perhaps a more direct interface to the ref count of a reference could be desirable. Perhaps a lvalue refcount() function to be used (mostly) like thus:

    refcount($ref)--;
    Update - Just to double check I used the following lvalue based subref which worked also.

    Well, I wouldn't have expected that to make a difference anyway...