http://qs1969.pair.com?node_id=20465

Buckaroo Buddha has asked for the wisdom of the Perl Monks concerning the following question:

@array = (5,5,null); $array[2] = $array[0] * $array[1]; print "$array[2]\n"; # output 25 $array[0] = 10; print "$array[2]\n"; # output 50
 
   if you know your code, you know that second 
   output statement is false.  

   you must re-calculate the value in $array2 to 
   get the output to come out as '50'

   does anyone know of a way to make $array2
   update itself automatically?

   i should warn you not to pop a blood vessel trying to 
   answer this for me ... i'm reasonably convinced that 
   i will simply update $array2 on every pass of the 
   loop

   but for interest's sake i'd like to know if i can do it
   the way i'd like to.  


   

 
  • Comment on how do i put an equasion in a variable, one which is evaluated at the time of use?
  • Download Code

Replies are listed 'Best First'.
Re: how do i put an equasion in a variable
by btrott (Parson) on Jun 29, 2000 at 23:22 UTC
    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?
Re: how do i put an equasion in a variable
by cwest (Friar) on Jun 29, 2000 at 23:06 UTC
    my $array = [ 5, 5 ]; $array->[2] = sub { $array->[0] * $array->[1] }; print &{$array->[2]}; # 25 $array->[1] = 10; print &{$array->[2]}; # 50
    Is this good enough?

    Update: You could also use eval:

    $array->[2] = '$array->[0] * $array->[1]'; print eval $array->[2];
    --
    Casey
    
Re: how do i put an equasion in a variable
by jlistf (Monk) on Jun 29, 2000 at 23:04 UTC
    i think this should work. make $array2 hold a subroutine closure. this way, every time you call $array2, the closure will be re-evaluated.