and a composite key that include both the name and value of the index would sort nicely.
If the number of elements at any given level can be larger than 10, you'd need to ensure your indices had leading zeros for a simple sort to work correctly.
For a potentially more efficient mechanism, you can pack the indices rather than joining them:
$array{ pack 'C*', @sortedIndices } = $somevalue;
Obviously, you chose a format ( 'C*', 'S*', 'N*' etc.) to suit the maximum range of your application. These packed composite keys sort very efficiently whilst avoiding the need for padding with leading zeros. Of course, you'll need to unpack the keys for display purposes, but that is a small price to pay for the efficiency during computation.
Using a hash has another advantage for your application--using variable depths in a single structue. Any given element of an array can only hold one value. That means that if you want to store leaf data and a deeper structure at the same position, you get into complications.
To explain that, say amongst your sets of indices you have (1,2) & (1,2,3). You code above would attempt to store a 'leaf' value at both of these set of indices; eg.
$array->[1][2] = 'the value'; ... sometime later $array->[1][2][3] = 'the value';
But 'the value' stored at $array->[1][2] is a scalar, not an array reference, so when the second assignment is attempted, you'll be overwriting 'the value' with an array reference and the former will be lost.
Or worse, you'll attempt those two statements in the reverse order and when you assign $array->[1][2] = 'the value'; you'll loose everything that had previously been stored below that point.
Using a composite-keyed hash, there is no conflict
$array->{ pack 'C*', 1, 2 } = 'the value'; $array->{ pack 'C*', 1, 2, 3 } = 'the value';
In reply to Re^5: multidimensional arrays
by BrowserUk
in thread multidimensional arrays
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |