ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
4.3. Changing Array SizeProblemYou want to enlarge or truncate an array. For example, you might truncate an array of employees that's already sorted by salary to list the five highest-paid employees. Or, if you know how big your array will get and that it will grow piecemeal, it's more efficient to get memory for it in one step by enlarging it just once than it is to keep Solution# grow or shrink @ARRAY $#ARRAY = $NEW_LAST_ELEMENT_INDEX_NUMBER; Assigning to an element past the end automatically extends the array: $ARRAY[$NEW_LAST_ELEMENT_INDEX_NUMBER] = $VALUE; Discussion
Here's some code that uses both: sub what_about_that_array { print "The array now has ", scalar(@people), " elements.\n"; print "The index of the last element is $#people.\n"; print "Element #3 is `$people[3]'.\n"; } @people = qw(Crosby Stills Nash Young); what_about_that_array(); prints:
whereas: $#people--; what_about_that_array(); prints:
Element #3 disappeared when we shortened the array. If we'd used the $#people = 10_000; what_about_that_array(); prints:
The $people[10_000] = undef; Perl arrays are not sparse. In other words, if you have a 10,000th element, you must have the 9,999 other elements, too. They may be undefined, but they still take up memory. For this reason, We have to say See AlsoThe discussion of the |