I was quite surprised to find that the keys function happily works with arrays:
keys HASH keys ARRAY keys EXPRReturns a list consisting of all the keys of the named hash, or the
indices of an array. (In scalar context, returns the number of keys or
indices.)
Is there any benefit in using keys @array instead of 0 .. $#array with respect to memory usage, speed, etc., or are the reasons for this functionality more of a historic origin?
Seeing that keys @array holds up to $[ modification, I’m guessing it’s historic :
$ perl -Mstrict -wE 'local $[=4; my @array="a".."z"; say join ",", keys @array;'
Use of assignment to $[ is deprecated at -e line 1.
4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29
The link you provided actually has one important reason you might use/not use
keys:That would cause
eachto reset to the beginning of the array. Usingkeysandeachwith arrays might be important if they ever natively support sparse arrays as a real data-type.All that said, with so many array-aware language constructs like
foreachandjoinin perl, I can’t remember the last time I used0..$#array.