| [reply] [d/l] |
$ret{$j}[$i]
is short for
$ret{$j}->[$i]
In lvalue context (e.g. on the left of a "="), -> and other dereference operators will autovivify the reference. That means dereference operators will automatically create a variable of the required variable type (e.g. ->[...] will create a hash) and place a reference to it in the variable being dereferenced. This only happens if the variable being dereferenced is undef. In other words,
$ret{$j}[$i]
is short for
( $ret{$j} //= [] )->[$i]
when used as an lvalue.
| [reply] [d/l] [select] |
$ret[$j][$i] = $tmp[i]; #just changed to square brackets
it will become an array of arrays?
| [reply] [d/l] |
Here’s a good way to think of it:
-
The only form of “array” (or list, or anything else) that Perl actually has, is one-dimensional. In every case, there is just a single index, or key or what-have-you, and it returns “one value” (or undef).
-
How-ever... that is plenty enough, be-cause that “value” can be, not just a single string or number or what-have-you, but also a reference to anything at all.
So, if we have a list of, say, 10 elements, and each of those lists refers to a list of elements, and each of those refers to a list, and once again each of those refers to a list ... whaddaya got? Well, you’ve got a 4-dimensional array. Properly speaking, you’ve got a 4-layer tree. And in this you have a data structure that is considerably more flexible, and considerably more efficient in its use of memory.
The so-called “auto-vivification” that was spoken of earlier simply means that Perl can make these elements appear on-demand, without obliging you to create messy syntax. You can simply say things like:
$$a{1}{2}{3}{4}
(where $$a can also equivalently be written $a-> .. it means the same thing)
... and Perl will automagically create all of the elements (for hash-keys 1, 2, 3, and 4). They come-to-life automatically, poof. (Hence, “auto-vivify.”)
You might have noticed that in the above code I didn’t actually refer to an array, but to a hash. That’s quite common.
And one more thing: get to know CPAN ... now. If you go to http://search.cpan.org and type in, “array,” you will (today) have 5,001 hits. No matter what you are doing, there’s a CPAN module to do it. Including, specifically, the efficient construction and management of large and/or sparse matrices. There’s a lot of voodoo-code in those packages, with hundreds or sometimes thousands of self-tests. You get the benefits of “all that voodoo,” without casting magick spells in your own code, and you can be certain that the code actually works.
When you say you want, “an n-dimensional array,” you really don’t want your code to be filled-up with the necessary Perl constructions. You merely assume that, in order to get what you want, that’ll be what you have to do. But that is frequently not the case. Search before you write. The most pre-eminent part of Perl, IMHO, is not the language: it’s the library.
| |