Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

An overloaded object and tie

by Anonymous Monk
on Jun 09, 2004 at 17:33 UTC ( [id://362816]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I've been struggling for hours - but I can't seem to get anywhere! Either I'm missing something simple, or it can't be done. Lets hope it's something simple:)

I have an overloaded object that can perform basic arithmetic:

$one=new Array_Like_Object(1); #set all elements to one<br> $two=new Array_Like_Object(2); #set all elements to two $three = $one + $two;

To set and read elements from this object I have a few simple methods:

$three->Read(14); #return element 14 $three->Write(14,3); #set element 14 to 3

I had assumed that in conjunction with tie, I could do something like:

$three(14); #return element 14 $three(14)=3; #set element 14 to 3

but I can't seem to get it to work. Would this kind of syntax be possible using a tied array?

Thanks.

Replies are listed 'Best First'.
Re: An overloaded object and tie
by eclark (Scribe) on Jun 09, 2004 at 18:02 UTC
      Hi, I've already tried this - it doesn't work in the way I thought/wanted it to:
      package Tie::NewStdArray; use Tie::Array; @ISA = ('Tie::StdArray'); sub STORE { print 'in store'; } sub FETCH { print 'in fetch'; } # all methods provided by default package main; my @somearray; my $object = tie @somearray,Tie::NewStdArray; $somearray[0]=12; #intercepted by tie $object[0]=12; #uses the blessed array
      Using the object returned from tie uses the blessed reference not the tie, which means you can't use the [] syntax when object are created on the fly by overloading. For example:
      $three=$two+$one; print $three[12];
Re: An overloaded object and tie
by adrianh (Chancellor) on Jun 09, 2004 at 20:01 UTC
    Would this kind of syntax be possible using a tied array?

    Not really. What you're probably after is overloading array references, rather than tieing. This would allow you to do:

    $three->[14]; $three->[14] = 3;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://362816]
Approved by sacked
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-04-25 14:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found