<?xml version="1.0" encoding="windows-1252"?>
<node id="989548" title="How can I re-program the exists function?" created="2012-08-24 10:06:03" updated="2012-08-24 10:06:03">
<type id="115">
perlquestion</type>
<author id="823564">
greengaroo</author>
<data>
<field name="doctext">
&lt;p&gt;Dear Monks,&lt;/p&gt;

&lt;p&gt;I have a good question for you.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Consider this module:&lt;/p&gt;

&lt;code&gt;
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;
&lt;/code&gt;

&lt;p&gt;Now this script:&lt;/p&gt;

&lt;code&gt;
use MyExists qw(my_exists);

my %hash = ( 'test1' =&gt; 'value1', 'test2' =&gt; '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";
&lt;/code&gt;

&lt;p&gt;The result is:&lt;/p&gt;

&lt;code&gt;
Real exists: 1
My exists: No!
Real exists:
My exists: No!
&lt;/code&gt;

&lt;p&gt;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?&lt;/p&gt;

&lt;p&gt;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!&lt;/p&gt;

&lt;p&gt;I started to look at the prototypes for subroutines and I didn't find a solution. No luck with Google either.&lt;/p&gt;

&lt;p&gt;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 .&lt;/p&gt;

&lt;p&gt;Thank you!&lt;/p&gt;

&lt;div class="pmsig"&gt;&lt;div class="pmsig-823564"&gt;
&lt;div class="pmsig"&gt;
  &lt;i&gt;There are no stupid questions, but there are a lot of inquisitive idiots.&lt;/i&gt;&lt;br/&gt;
&lt;div class="pmsig-823564"&gt;
  -- [id://823564]
&lt;/div&gt;&lt;/div&gt;

&lt;/div&gt;&lt;/div&gt;</field>
</data>
</node>
