in reply to Using exists to check element in array

Use defined instead of exists.

Replies are listed 'Best First'.
Re^2: Using exists to check element in array
by LanX (Saint) on Jan 29, 2024 at 15:26 UTC
    This won't help with existing undefined values.

    Exist is the logical choice in his use case, and he asked for the rationale.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery

      and he asked for the rational.

      Hasn't that been answered already?

      It's because exists $a[i] doesn't really check if the element exists in the array. It's not sufficient for the element to be part of the array; the pointer in the array buffer must be something other than NULL.

      For example,

      my @a; $a[1] = undef; $a[2] = 0; $a[3] = 7;
      Element of the arrayexistsdefinedTrue
      $a[0]YesNoNoNo
      $a[1]YesYesNoNo
      $a[2]YesYesYesNo
      $a[3]YesYesYesYes
      $a[4]NoNoNoNo

      It might also be warning of problems with using NULL as a special value. I suspect Perl is quite consistent at keeping NULL elements NULL, but there might be surprise cases (for (@a)? for ((), @a)? f(@a)?)

      Update: Replaced some uses of "exists".

        To misquote Bill Clinton:

        "It depends if your meaning of exist exists."

        ;)

        Your table shows exactly a consistent behavior to exists when used with hashes. Unset values just don't exist.

        $a[0] was never set, hence it doesn't exist.

        I wasn't sure what you and sectokia meant with null-pointer, apparently it's the C-value of unset "gap" values¹ in the underlying C-array.

        But those exist only on the C level, not logically in Perl.

        > but there might be surprise cases (for (@a)? for ((), @a)? f(@a)?)

        I don't understand, probably above my expertise.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        see Wikisyntax for the Monastery

        ¹) with an index smaller than the maximal index of a set value

      It will help if undef isn't an acceptable value, which is a common scenario.

      I should have qualified my answer, but I thought the OP said they were storing numbers. Those are the keys, though. woops.