You are running into autovivification.

$ perl -le'undef $_; defined $_->{0}; print $_' HASH(0x813f1c8)

Whenever you try to dereference an undefined value, Perl will helpfully summon an anonymous data type of the corresponding type and store it there. In your case, the culprit is probably

while( defined $bros->{ $find }->[ $index ]->{ $key } ) { # ... }

If you use exists there instead, your ghost hashes should go away. Actually, no, they won't. The hash is summoned by the mere attempt at dereferencing. You have to make sure that $bros->{ $find }->[ $index ] exists before attempting a dereference:

while( ref $bros->{ $find }->[ $index ] and defined $bros->{ $find }->[ $index ]->{ $key } ) { # ... }

However, in Perl, it's almost always a mistake to use a counter variable such as $index when you only ever use it as an index into a single structure. This is one of the red flags mentioned in Mark-Jason Dominus' excellent Program Repair Shop and Red Flags article series. You could have avoided the issue altogether by rewriting your inner loop to a foreach:

for my $year ( qw( 1958 1959 1960 1961 1962 1963 1964 ) ) { for my $film ( @{ $bros->{ $year } } ) { push @res, { brother => $film, year => $year } if $film->{ $key } =~ /$data/i; } }

Depending on taste that can be transformed to a grep:

for my $year ( qw( 1958 1959 1960 1961 1962 1963 1964 ) ) { push @res, ( map +{ brother => $_, year => $year }, grep $_->{ $key } =~ /$data/i, @{ $bros->{ $year } }, ); }

Makeshifts last the longest.


In reply to Re^5: Using grep to remove array element from HoAoH leaving empty array-hash element by Aristotle
in thread Using grep to remove array element from HoAoH leaving empty array-hash element by Popcorn Dave

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.