Dear Monks,
I have a good question for you.
Lets say I want to re-program the "exists" function. Of course, that is not my end goal, but I will use this as an example because it will be easier to explain.
Consider this module:
package MyExists; use Exporter qw( import ); @EXPORT = qw(my_exists); sub my_exists { my ($string) = @_; if ( eval("exists($string)") ) { return "Yes!"; } else { return "No!"; } } 1;
Now this script:
use MyExists qw(my_exists); my %hash = ( 'test1' => 'value1', 'test2' => 'value2' ); print "Real exists: "; print exists( $hash{'test1'} ); print "\n"; print "My exists: "; print my_exists( $hash{'test1'} ); print "\n"; print "Real exists: "; print exists( $hash{'test3'} ); print "\n"; print "My exists: "; print my_exists( $hash{'test3'} ); print "\n";
The result is:
Real exists: 1 My exists: No! Real exists: My exists: No!
Now, my real question is: How can you create a function that would act like the "exists" function? In other words, I need to build a function that is able to receive an expression and not a value (like "my_exists" actually does). According to perldoc, "exists" receives and "EXPR". How can I do that myself?
If I pass '$hash{"test1"}' as a string, then I could probably evaluate it right? Wrong! My function doesn't know what $hash is because its not declared in the Module!
I started to look at the prototypes for subroutines and I didn't find a solution. No luck with Google either.
I have a workaround. In short, I pass two arguments, first the HashRef: \%hash, then the string: '$hash{"test1"}'. It works but I would really like to know how to do it the "exists" way .
Thank you!
In reply to How can I re-program the exists function? by greengaroo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |