Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: how do i put an equasion in a variable

by btrott (Parson)
on Jun 29, 2000 at 23:22 UTC ( #20478=note: print w/ replies, xml ) Need Help??


in reply to how do i put an equasion in a variable, one which is evaluated at the time of use?

You could use closures, as has already been mentioned, or you could use tie. Something like this might work for you... I don't know.

package Product; use Tie::Array; @ISA = qw/Tie::StdArray/; use strict; sub TIEARRAY { my $class = shift; bless [ @_ ], $class; } sub FETCH { my $them = shift; my $index = shift; return $index >= @$them ? eval join '*', @$them : $them->[$index]; } package main; ## Initialize your array with 2 elements, 8 and 2 tie my @p, 'Product', 8, 2; print $p[2], "\n"; ## Change the second element to 5 $p[1] = 5; print $p[2], "\n"; ## You can even add new elements to the array; now ## you need to use $p[3] to get the product push @p, 10; print $p[3], "\n";
This is, admittedly, pretty hackish. But it works. :)

Output:

16 40 400
If you try to access any element beyond the end of the array, it returns the product of the elements in the array. Admittedly, I don't really like those semantics much--anyone have any better ideas?


Comment on Re: how do i put an equasion in a variable
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://20478]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (20)
As of 2015-07-06 12:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (74 votes), past polls