in reply to Using exists to check element in array

Because people tend to confuse defined and exists with array-elements. Especially when using delete on array-elements. ¹

We had recently a discussion covering this, see Re^3: extracting a list element ( 'delete @array' explained) and connected thread.

> In my situation the numerical keys ($elementIndex) are not contiguous

Personally I think if you really know what you are doing, you should just silence this warning.

NB: But sparse arrays with gaps of non-existing elements are normally more efficiently implemented with hashes.²

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

updates

¹) and because Data::Dumper is kind of lying about non-existing elements.

²) and hashes have the advantage that the number of existing keys is readily available. The length of an array with gaps OTOH is of no help, especially because after a delete all non-existing entries will be truncated from the end.

  • Comment on Re: Using exists to check element in array

Replies are listed 'Best First'.
Re^2: Using exists to check element in array
by david (Novice) on Jan 28, 2024 at 10:09 UTC

    Thanks @Rolf. I did change to using a hash, which works fine, it is just slightly messier when it comes to string concatenation because of the double quotes I find I need to put around the keys.

    Thanks for link, I had a read.
      > messier when it comes to string concatenation because of the double quotes I find I need to put around the keys.

      In Perl keys are auto-quoted!

      I.e. this "txt $h{key} txt" works fine.

      You are also free to use hash-slices for multiple values, like "txt $h{@keys} txt"

      update

      From Learning Perl

        Unquoted Hash Keys

        Perl offers many shortcuts that can help the programmer, such as omitting the quote marks on some hash keys.

        You can’t omit the quote marks on every key since a hash key may be any arbitrary string. But keys are often simple. If the hash key only consists of letters, digits, and underscores without starting with a digit, you may be able to omit the quote marks. This kind of simple string without quote marks is called a bareword since it stands alone without quotes.

        One place you are permitted to use this shortcut is the most common place a hash key appears, which is in the curly braces of a hash element reference. For example, instead of $score{"fred"}, you could write $score{fred}. Since many hash keys are like this, not using quotes is a convenience. But beware: if there’s anything inside the curly braces besides a bareword, Perl will interpret it as an expression.

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

        Thanks, I re-checked and the double quotes were an error!!! Glad you inspired me go back and check and find this. Doh! Thanks. Much easier to read now too!