How do you use memory leaks and circular refs (weak refs) with a short example?

In Perl, memory leaks can occur when circular references are created between objects, preventing them from being properly garbage collected. To manage this, we can use weak references, allowing one object to reference another without increasing its reference count, thus avoiding circular dependencies.

Below is a short example demonstrating how to create circular references and manage them using weak references.

use strict; use warnings; use Scalar::Utils 'weaken'; # Class definition for Node package Node; sub new { my ($class, $name) = @_; my $self = { name => $name, next => undef }; bless $self, $class; return $self; } # Method to set the next node sub set_next { my ($self, $next_node) = @_; weaken($self->{next} = $next_node); # Create a weak reference } # Method to display node information sub display { my $self = shift; print "Node: " . $self->{name} . "\n"; if (defined $self->{next}) { print "Next Node: " . $self->{next}->{name} . "\n"; } else { print "No next node.\n"; } } # Main script package main; my $node1 = Node->new("Node 1"); my $node2 = Node->new("Node 2"); $node1->set_next($node2); $node2->set_next($node1); # This creates a circular reference $node1->display(); $node2->display(); # Now, when we go out of scope, memory will be freed properly due to weak references.

Perl memory leaks circular references weak references garbage collection