develooper Front page | perl.perl5.porters | Postings from April 2000

overloading = [a solution]

Thread Previous | Thread Next
From:
Jeff Pinyan
Date:
April 24, 2000 19:41
Subject:
overloading = [a solution]
Message ID:
Pine.GSO.4.21.0004242236540.28375-100000@crusoe.crusoe.net
Here's a possible solution for "overloading" =, in scalars.

  # file:  test
  use Tie::AssignWrapper;
  use Example;

  tie $foo, 'Tie::AssignWrapper', 'Example', 100;
  print $foo - 5, $foo, $foo + 5;
  $foo = 25;
  print $foo - 2, $foo, $foo + 2;


  # file:  Tie/AssignWrapper.pm
  package Tie::AssignWrapper;

  sub TIESCALAR {
    my ($class,$module,$value) = @_;
    my $self = [ $::{"${module}::"}, $module ];
    $self->[2] = $self->[0]{__store}->($value);
    return bless $self, $class;
  }

  sub FETCH {
    my $self = shift;
    return bless \$self->[2], $self->[1];
  }

  sub STORE {
    my ($self,$value) = @_;
    return bless \($self->[2] = $self->[0]{__store}->($value)), $self->[1];
  }

  1;


  # file:  Example.pm
  package Example;

  use overload (
    '+0' => \&__fetch,
    '""' => \&__fetch,
    fallback => 1,
  );

  sub __fetch { ${+shift}   }
  sub __store { sqrt(shift) }

  1;
  

Questions?  Comments?  Concerns?  Flames?

-- 
MIDN 4/C PINYAN, NROTCURPI, US Naval Reserve             japhy@pobox.com
http://www.pobox.com/~japhy/                  http://pinyaj.stu.rpi.edu/
PerlMonth - An Online Perl Magazine            http://www.perlmonth.com/
The Perl Archive - Articles, Forums, etc.    http://www.perlarchive.com/


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About