The Perl definition of many common words is not quite what you think. The question which you meant to ask is "How can I tell if a variable is 'declared'"? 'Defined' means that a variable has a value. This makes no sense if it is not 'declared'. 'Exists' refers to keys in a hash and has nothing to do with variables. The concept of storing the name of a variable in another variable is called 'symbolic reference'. It is never needed and always discouraged. In fact, one advantage of 'use strict' is that it prevents us from using symbolic reference by accident. To return to your original question, there is no run-time support to test if a variable is 'declared' ('Use strict' provides compile-time support). This would only be useful with symbolic reference which you should not be using anyhow.

UPDATE: I took it as a challenge to do what you asked for using strict vars with eval.

use warnings; use Test::Simple tests => 3; # Test wether or not the target of a symbolic reference is declared. my $xxx ; our $yyy; { use strict vars; my $sym_ref; $sym_ref = '$xxx'; ok ( do{eval $sym_ref; !$@}, 'declared lexical'); $sym_ref = '$yyy'; ok ( do{eval $sym_ref; !$@}, 'declared package'); $sym_ref = '$zzz'; ok (!do{eval $sym_ref; !$@}, 'not declared'); # Note: !do..... }

This test does what you wanted, but not what you need because symbolic-refs only work with package variables. Of course once you know that the variable is declared, you could use LanX's idea and check if the name 'exists' in the symbol table. Even that could fail in special cases. DO NOT USE SYMBOLIC REFERENCE!

Bill

In reply to Re: detecting an undefined variable by BillKSmith
in thread detecting an undefined variable by LloydRice

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.