$h4X4_|=73}{ has asked for the wisdom of the Perl Monks concerning the following question:

I have some thing happening in a package that seems strange to me. Lets say I have a blank array @array = (); when I check if the array{hash} is defined that should not be. Then push to that array and check the number again the array shifts to the next number.
I hope the code explains it better...

#!/usr/bin/perl use warnings; use strict; # add to @Foo::THING push(@Foo::THING, { 'check' => '1',} ); # Should say "Some Thing" Foo::check_THING(0) ? print "Some Thing\n" : print "No Thing\n"; # Should say "No Thing" Foo::check_THING(1) ? print "Some Thing\n" : print "No Thing\n"; # add to @Foo::THING push(@Foo::THING, { 'check' => '1',} ); # Check if it was added? Foo::check_THING(1) ? print "Some Thing\n" # I think it should be this : print "No Thing\n"; # But we get this # Why is it 2? Foo::check_THING(2) ? print "Some Thing\n" # WTF? : print "No Thing\n"; package Foo; our @THING = (); sub check_THING { my $id = shift; defined $THING[$id]{check} ? return 1 : return 0; }

Replies are listed 'Best First'.
Re: Array skips number if checked for defined.
by Athanasius (Archbishop) on Jun 26, 2016 at 14:35 UTC

    Hello $h4X4_|=73}{,

    To expand a little on hippo’s answer: If you print out the contents of @Foo::THING immediately after the statement beginning Foo::check_THING(1), you’ll see an additional, empty, anonymous hash has been autovivified by the action of referring to $THING[1]{check}1:

    0:20 >perl 1665_SoPW.pl Some Thing No Thing [{ check => 1 }, {}] No Thing Some Thing 0:20 >

    (I’m using Data::Dump.) And if you add this line:

    no autovivification;

    immediately before the line our @THING = ();, you’ll get the behaviour you expect:

    0:20 >perl 1665_SoPW.pl Some Thing No Thing [{ check => 1 }] Some Thing No Thing 0:24 >

    (See the autovivification pragma.)

    1Note that you can replace check with any key name here and get the same result.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Array skips number if checked for defined.
by hippo (Archbishop) on Jun 26, 2016 at 14:06 UTC
Re: Array skips number if checked for defined.
by FreeBeerReekingMonk (Deacon) on Jun 26, 2016 at 14:59 UTC
    Alternatively, if you change your check function to:

    sub check_THING { my $id = shift; return 0 unless defined $THING[$id]; defined $THING[$id]{check} ? return 1 : return 0; }

    you get:

    Some Thing No Thing Some Thing No Thing