in reply to problem with variables in hash values??
In response to belg4mit's advice: Consider a *reference* to a variable,
I recommend references and anonymous subroutines like the updated following:
#!/usr/bin/perl -w use strict; ## variables my $magic = 2; my $sub = sub { $_[0] * $_[1] }; # sub ref my %item; ## subroutine sub tpl { $magic * 3 }; ## populate our hash $item{ '1' } = \$magic; # ref $item{ 'dbl' } = sub { $magic * 2 }; # anonymous sub $item{ 'tpl' } = sub { &tpl() }; # anon sub calls sub $item{ 'x' } = sub { $sub->( $magic, $_[0] ) }; # anon sub calls sub ref ## fool with $magic value, ## display results print "Magic: $magic\t1: ", ${$item{1}}, "\tdbl: ", &{$item{ 'dbl' }}(), "\ttpl: ", $item{ 'tpl' }->(), "\tx(4): ", $item{ 'x' }->(4), "\n"; $magic += 1; print "Magic: $magic\t1: ", ${$item{1}}, "\tdbl: ", $item{ 'dbl' }->(), "\ttpl: ", &{$item{ 'tpl' }}(), "\tx(4): ", $item{ 'x' }->(4), "\n"; $magic -= 1; print "Magic: $magic\t1: ", ${$item{1}}, "\tdbl: ", &{$item{ 'dbl' }}(), "\ttpl: ", $item{ 'tpl' }->(), "\tx(4): ", &{$item{ 'x' }}(4), "\n"; $magic *= 5; print "Magic: $magic\t1: ", ${$item{1}}, "\tdbl: ", $item{ 'dbl' }->(), "\ttpl: ", &{$item{ 'tpl' }}(), "\tx(4): ", $item{ 'x' }->(4), "\n"; ## we're good print "Done\n\n"; exit(0);
there is quite a bit in there to play with, but it should show you how to use references and anonymous subroutines. notice the different syntax you can use, &{$item{'x'}}(4) and $item{'x'}->(4). be aware, though, that there is no parameter validation, and the output is sloppy
I'm also VERY new at this, so please be gentle
sub referrences are generally daunting, and not so gentle, for the new. but, once you get over your initial fear, they really aren't too difficult to understand.
for more information, look here for tye's tutorial on reference
here and here for a little info on "closures", which build on subroutine references
and, as mentioned above, perlref
hang in there, and piece through the code and few links i gave you. while they may not answer your question out right, they are a start.
Will perl for money
JJ Knitis
(901) 756-7693
gt8073a@industrialmusic.com
|
|---|