Why? Declaring the variable takes virtually no CPU time. A declared but undefined variable doesn't take up much memory. There is nothing I know of that tests for the existence of a variable, so I don't see how you could be using its existence to make a decision later on. Unless you've got a million of these you want to do, I don't see why not just declare the variable all the time, and only define it under the $xyz condition. If you do have a million, your code would be a mess, anyway.
If you really insist on this, I don't know how to do it with a variable, but it could be done with a key of a global hash:
use warnings; use strict;
my %global;
try($_) for 0,0,0,1,0;
sub try {
my $xyz = shift;
if($xyz) { $global{globalvar} = undef; }
printf "try(%d) => globalvar %s\n", $xyz, exists $global{globalvar
+} ? "exists" : "doesn't exist";
}
__END__
try(0) => globalvar doesn't exist
try(0) => globalvar doesn't exist
try(0) => globalvar doesn't exist
try(1) => globalvar exists
try(0) => globalvar exists
Maybe you could do it with eval of some sort, like below... but I'm not sure that line 9 doesn't vivify $main::globalvar anyway.
use warnings;
use strict;
my $xyz = 0;
if($xyz) { eval { $main::globalvar = undef; print STDERR __LINE__, ":
+eval'd\n"} }
printf "%d: if(%d) => didn't eval\n", __LINE__, $xyz;
$xyz = 1;
if($xyz) { eval { $main::globalvar = undef; print STDERR __LINE__, ":
+eval'd\n"} }
printf "%d: if(%d) => did eval => '%s'\n", __LINE__, $xyz, defined $ma
+in::globalvar ? $main::globalvar : '<undef>';
What is it you're really trying to accomplish with this? |