in reply to Re^7: Using a sting with a variable name
in thread Using a sting with a variable name

Sorry, I used the wrong var name. What I meant is that fixing the failing case below and will cause the third to fail.

uuse strict; use warnings; no strict 'vars'; use Test::More tests => 3; sub var_exists { my ($var) = @_; return defined ${substr $var, 1}; } { no warnings 'once'; $var1 = 'a'; $var2 = undef; @var3 = qw( a b c ); } ok(var_exists('$var1'), 'var1'); ok(var_exists('$var2'), 'var2'); ok(!var_exists('$var3'), 'var3');
1..3 ok 1 - var1 not ok 2 - var2 # Failed test 'var2' # at a.pl line 20. ok 3 - var3 # Looks like you failed 1 test of 3.

Replies are listed 'Best First'.
Re^9: Using a sting with a variable name
by JavaFan (Canon) on May 11, 2009 at 17:57 UTC
    From a Perl (language!) point of view, there's no difference between a package variable that hasn't been used, and a package variable which is undefined. The following, after all, is a valid Perl program; it compiles and runs:
    print $foo;
    it may warn, but it's valid.

    It only matters in the implementation, and in the few edge cases where you can poke into the underlaying implementation.

      So why bother using use strict; if it doesn't matter whether a variable exists or not. That perl doesn't care says nothing about whether the programmer cares or not.

      Note I never said that the OP cares. I even said he might not ("I don't know if that's ok or not."). I'm just outlining the possibilities the OP might be interested in.

        Considering this entire exercise is only going to work with package variables, and we have to disable strict 'refs' for it to work in the first place, I don't really get your remark about use strict;.

        Package variables are Perl4 left overs. The era predating strict. And lexicals. When Perl variables were much more like AWK or Shell.

        And do get your capitalization right when it matters. perl cares, because perl is the implementation. But in the language, Perl, you can use any package variable you want, at any time*, without making any declaration you intent to use the variable.

        *You may, however, be forced to use the fully qualified name.