Memory use of sparse arrays in Perl

A few days ago, one of the Perl Maven readers asked me about indexing in arrays in Perl, and then he was wondering if arrays
that only have elements in some high index are sparse arrays? In other words if we have an array with a single value at index
1,000,000 does Perl allocate space for all the preceding 1,000,000 elements, or is does it take up place for the single element in
the array.

In yet other words, how much memory does this use?

my @a;
$a[1_000_000] = 1;

We could read the documentation and probably find the answer somewhere, or we could do a little experiment.

As you can see the memory usage of the array growth as the index of the single element in the array growth. So the arrays in Perl don't have any special
memory-saving algorithm for sparse arrays.

If we need to hold a few values in a data structure with various random large indexes, we can use a hash instead.
The size of the hash only growth as the length of the key. So the key 1,000,000 that has 7 characters in it will take up 6 bytes more than the key 0
which has 1 character in it.

The drawback of using hash is that we can't use array-operations on it such as push, pop, etc.
and that the values are not sorted. We can fetch the keys of the hash, but they will return in random order.