in reply to Re: Using exists to check element in array
in thread Using exists to check element in array

Thanks. This is really interesting. I thought under "normal" circumstances memory allocation for variables was fairly fixed and persistent for PERL and was the reason that 'referencing' works. Perhaps a little knowledge is truely dangerous but I have to push through to turn a little into a little-more, so thanks for the input. Does CV stand for "Code Value"? I found that in 'perlguts' which was pretty heavy reading!

Musings... It seems to me that it is fairly reasonable for a user to want to know if an element of an array or hash 'exists'. Exists could return more than a binary choice and the user could be expected to test the returned value to make sure it is what they wanted. I am guessing that a fairly large portion of PERL code includes arrays and hashes, so predictable results in this area now and in the future seems important. I wonder what code may break in the future and indeed where I might have used it previously and erroneously! The warning certainly made me stop but I needed the why and the guidance on what to do instead.

Thanks again to you and the other contributors.

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

Replies are listed 'Best First'.
Re^3: Using exists to check element in array
by sectokia (Friar) on Mar 07, 2024 at 00:26 UTC

    Its because the 'high level' concept of an Array is that it is a string of 0 to n items. So all items in the array always exist conceptually.

    So if you want to know if index x 'exists' in the array, simply do either: (x <= $#array) or (x < scalar @array).

    If you haven't set an array index to a value, then its value will be undef and you can check this simply with (defined $array[x]). If x is beyond the length of array, this will not change the length of the array. However if you assign an index to a value - including undef, the array will expand in size to at least that index.

    .