in reply to Re^2: eval, Read environment variable and expand using eval
in thread eval, Read environment variable and expand using eval

There is a subtle yet important difference between defined and exists on hash and array elements. Defined will autovivify your hash element and make its value undefined.

Perhaps you meant this?

$r = (exists $ENV{INFORMIXSQLHOSTS}) ? $ENV{INFORMIXSQLHOSTS} : 'sqlho +st')

If you want to check every possiblity this would be the best. However I usually just do the exists() check.

$r = ((exists $ENV{INFORMIXSQLHOSTS} && defined($ENV{INFORMIXSQLHOSTS} +) && length($ENV{INFORMIXSQLHOSTS}) ) ? $ENV{INFORMIXSQLHOSTS} : 's +qlhost'));

Replies are listed 'Best First'.
Re^4: eval, Read environment variable and expand using eval
by Anonymous Monk on Feb 19, 2010 at 15:04 UTC
    No, defined does not autovivify
    my %f; warn snot => defined $f{snot}; warn snot => exists $f{snot}; __END__ snot at - line 3. snot at - line 4.
      Darnit. I thought defined() autovivified simple hashes. Both exists and defined still can autovivify on deep hashes though.
      #!/usr/bin/perl # use warnings; use Data::Dumper; my $h = { 'foo' => 1 }; if(exists($h->{notexist}{baz})){ } if(defined($h->{notdefined}{baz})){ } print Dumper($h); exit 0;
      $VAR1 = { 'notexist' => {}, 'foo' => 1, 'notdefined' => {} };

        Both exists and defined still can autovivify on deep hashes though.

        No, it's the dereference operator that does the autovivification. Any autovivification occurs before defined and exists are called.

        $ perl -MData::Dumper -e'$h{notexist}{baz}; print Dumper \%h' $VAR1 = { 'notexist' => {} };
        no, neither exist nor define autovivify. you're treating notexist and notdefined as if they exist and are defined, therefore they are autovivified (start existing, you treat as hash, become hash)
        #!/usr/bin/perl -- use strict; use warnings; use Data::Dumper; my %f; if ( $f{notexist}{baz} ) { warn 1} if ( $f{notdefined}{baz} ) { warn 1} die Dumper(\%f); __END__ $VAR1 = { 'notexist' => {}, 'notdefined' => {} };