Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.30 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.    sub new {
  9.       my ($class, %args) = @_;
  10.       my $voltage = $args{voltage} // 0;
  11.       my $self = bless({}, $class);
  12.       $self->{voltage} = $voltage;
  13.       $self->{parent} = $self;            # Memory leak.
  14.       return $self;
  15.    }
  16.  
  17.    sub _tail {
  18.       my ($self) = @_;
  19.       $self = $self->{parent} while $self != $self->{parent};
  20.       return $self;
  21.    }
  22.  
  23.    sub get_voltage {
  24.       my ($self) = @_;
  25.       return $self->_tail()->{voltage};
  26.    }
  27.  
  28.    sub set_voltage {
  29.       my ($self, $voltage) = @_;
  30.       $self->_tail()->{voltage} = $voltage;
  31.    }
  32.  
  33.    sub fuse {
  34.       my ($self, $src) = @_;
  35.       $self->_tail()->{parent} = $src;
  36.    }
  37.  
  38.    $INC{"Wire.pm"} = 1;
  39. }
  40.  
  41.  
  42. my $o1 = Wire->new( voltage => 1 );
  43. my $o2 = Wire->new( voltage => 2 );
  44. my $o3 = Wire->new( voltage => 3 );
  45. my $o4 = Wire->new( voltage => 4 );
  46.  
  47. say join " ", map $_->get_voltage(), $o1, $o2, $o3, $o4;  # 1 2 3 4
  48.  
  49. $o2->fuse($o1);
  50. $o3->fuse($o4);
  51. $o1->fuse($o3);
  52.  
  53. say join " ", map $_->get_voltage(), $o1, $o2, $o3, $o4;  # 4 4 4 4
  54.  
  55. $o1->set_voltage(5);
  56.  
  57. say join " ", map $_->get_voltage(), $o1, $o2, $o3, $o4;  # 5 5 5 5
  58.  
  59. $o3->set_voltage(6);
  60.  
  61. say join " ", map $_->get_voltage(), $o1, $o2, $o3, $o4;  # 6 6 6 6
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement