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?


In reply to Re: how do i create a global var conditionally? by pryrt
in thread how do i create a global var conditionally? by perltux

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.