Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.50 KB | None | 0 0
  1. use strict;
  2. use warnings qw( all );
  3. use feature qw( say );
  4.  
  5. BEGIN {
  6.    package Wire;
  7.  
  8.    use Scalar::Util qw( weaken );
  9.  
  10.    sub new {
  11.       my ($class, %args) = @_;
  12.       my $voltage = $args{voltage} // 0;
  13.       my $self = bless({}, $class);
  14.       $self->{voltage} = $voltage;
  15.       weaken( $self->{parent} = $self );
  16.       return $self;
  17.    }
  18.  
  19.    sub _tail {
  20.       my ($self) = @_;
  21.       $self = $self->{parent} while $self != $self->{parent};
  22.       return $self;
  23.    }
  24.  
  25.    sub get_voltage {
  26.       my ($self) = @_;
  27.       return $self->_tail()->{voltage};
  28.    }
  29.  
  30.    sub set_voltage {
  31.       my ($self, $voltage) = @_;
  32.       $self->_tail()->{voltage} = $voltage;
  33.    }
  34.  
  35.    sub fuse {
  36.       my ($self, $src) = @_;
  37.       $self->_tail()->{parent} = $src;
  38.    }
  39.  
  40.    sub DESTROY {
  41.       say "Destroying $_[0]";
  42.    }
  43.  
  44.    $INC{"Wire.pm"} = 1;
  45. }
  46.  
  47.  
  48. {
  49.    my $o1 = Wire->new( voltage => 1 );
  50.    my $o2 = Wire->new( voltage => 2 );
  51.    my $o3 = Wire->new( voltage => 3 );
  52.    my $o4 = Wire->new( voltage => 4 );
  53.  
  54.    say join " ", map $_->get_voltage(), $o1, $o2, $o3, $o4;  # 1 2 3 4
  55.  
  56.    $o2->fuse($o1);
  57.    $o3->fuse($o4);
  58.    $o1->fuse($o3);
  59.  
  60.    say join " ", map $_->get_voltage(), $o1, $o2, $o3, $o4;  # 4 4 4 4
  61.  
  62.    $o1->set_voltage(5);
  63.  
  64.    say join " ", map $_->get_voltage(), $o1, $o2, $o3, $o4;  # 5 5 5 5
  65.  
  66.    $o3->set_voltage(6);
  67.  
  68.    say join " ", map $_->get_voltage(), $o1, $o2, $o3, $o4;  # 6 6 6 6
  69. }
  70.  
  71. say "Any \"Destroying\" message after this point indicates a memory leak.";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement