in reply to Re: Help tightening up a subroutine please
in thread Help tightening up a subroutine please

These may not always be true, but they autovivify an element so *will* be true the second time over you test them with the same key.

I don't think that's true.

my %x; print "one\n" if defined %{$x{a}}; print "two\n" if defined %{$x{a}}; print Dumper( \%x );

It does autovivify, but it does so to a value that's still not defined (when tested that way, anyway). Full output:

$VAR1 = { 'a' => {} };

UPDATE: I should add that I do not think this is a good way to do this check. It would be better to check that the key exists and then, if you need to know that there's something in there, dereference the array and check that.

Replies are listed 'Best First'.
Re^3: Help tightening up a subroutine please
by gaal (Parson) on Jan 23, 2007 at 22:06 UTC
    Huh. You sent me to the manual since this greatly surprised me. FWIW you're right—thanks for the correction—but some of what I did remember does hold:

      Use of "defined" on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate has ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size:

      if (@an_array) { print "has array elements\n" } if (%a_hash) { print "has hash members\n" }

      When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use "exists" for the latter purpose.

Re^3: Help tightening up a subroutine please
by ikegami (Patriarch) on Jan 23, 2007 at 18:49 UTC

    Update: Bah, I should head my own advice. The second statement never gets a chance to execute.

    You're looking at the statements in isolation. Look at them as a pair.

    Original post: (WRONG!)

    # First time next unless defined %{$matches{$fasta_id}}; # False last unless defined @{$matches{$fasta_id}{$site}}; # False # Second time next unless defined %{$matches{$fasta_id}}; # Now true!! last unless defined @{$matches{$fasta_id}{$site}};

    What really happens:

    # First time next unless defined %{$matches{$fasta_id}}; # False -> next last unless defined @{$matches{$fasta_id}{$site}}; # Skipped by next # Second time next unless defined %{$matches{$fasta_id}}; # Still false last unless defined @{$matches{$fasta_id}{$site}};