The A object formerly referenced by $obj will not go away until the program exits, even after $obj itself is undefed. Why? Because there's a B object that references it. And that B object won't go away because that A object references it too. So it's like the A and B are pointing at each other, keeping each other alive (this is called a circular reference.)package A; sub new { my $class = shift; my $this = bless {}, $class; $this->{-twin} = new B(-twin => $this); return $this; } package B; sub new { my $class = shift; bless {@_}, $class; } $obj = new A; undef $obj;
Perl 5.6 added some magic called a 'weak reference'.
See the 'weaken'? That specific reference is now "weak", and does not actually add to the reference count (so the only reference to the A object is $obj). When $obj is then undefined, the reference count goes to zero, and any weak references are automatically set to undef by Perl. It's perfect for when you need backreferences that should not keep their referents alive.package A; sub new { my $class = shift; my $this = bless {}, $class; $this->{-twin} = new B(-twin => $this); return $this; } package B; sub new { my $class = shift; my $this = bless {@_}, $class; weaken $this->{-twin}; return $this; } $obj = new A; undef $obj;
This makes it very easy to convert a function that displays text to STDOUT into one returning its output as a string:$bar = "this\nthat\n"; open(FH, '<', \$bar); $this = <FH>; # reads "this\n" $that = <FH>; # reads "that\n" open(FH, '>', \$bar); print FH "this\n"; print FH "that\n";
# $foo = capture { print 'hi'; } # $foo will be filled as if someone had done $foo = `perl -e { print ' +hi'; }` or something like that # if the sub prints directly to STDOUT, like: print STDOUT 'hi'; then + the output will not be captured sub capture(&) { my ($oldsel, $fh, $ret); open($fh, '>', \$ret) or die "can't capture: $!"; $oldsel = select($fh); &{$_[0]}; select $oldsel; close($fh); $ret; }
$"=$,,$_=q>|\p4<6 8p<M/_|<('=> .q>.<4-KI<l|2$<6%s!<qn#F<>;$, .=pack'N*',"@{[unpack'C*',$_] }"for split/</;$_=$,,y[A-Z a-z] {}cd;print lc
In reply to Re: The latest & greatest in 5.8.x?
by Stevie-O
in thread The latest & greatest in 5.8.x?
by drewbie
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |