perl.beginners
[Top] [All Lists]

Re: array within array

Subject: Re: array within array
From: Dr.Ruud
Date: Mon, 29 Oct 2007 17:26:37 +0100
Newsgroups: perl.beginners

Andrew Curry schreef:

> be very careful with exists, it auto creates the structure
>     use Data::Dumper;
>     my %hash;
>     if (exists $hash{a}{b}) {}
>     print Dumper(\%hash)
> then the next time you use exists it is there.
> defined is much safer as it doesnt do this.

No, the difference here is not between exists() and defined().

To be able to check the definedness (or the existence) of $h{foo}{bar},
$h{foo} is created first (auto-vivification).

Neither exists() nor defined() short-cuts hash-levels.


    perl -MData::Dumper -wle'
        my %hash;
        if ( defined $hash{foo}{bar} ) {};
        print Dumper \%hash;
    '
    $VAR1 = {
              'foo' => {}
            };

(same with exists())


Solution: test $h{foo} first:

    if ( exists( $hash{foo}      ) and
         exists( $hash{foo}{bar} ) )
    { ... }

-- 
Affijn, Ruud

"Gewoon is een tijger."


<Prev in Thread] Current Thread [Next in Thread>