4 ms·
I don't have the time to read through the whole article right now but the first section I skimmed 'Hard to build data structures' was wrong: ----------- @b=([
by weare138 4y ago
I don't have the time to read through the whole article right now but the first section I skimmed 'Hard to build data structures' was wrong:
-----------
@b=([(0.8,0.9,1)],2,3,4);
when we created the list. The []s enter a reference to the inner list as the first element of the outer list instead of flattening the inner list into the outer one.
OK. So we try again:
$b[0]
gives us
ARRAY(0xb75eb0)
So obviously we manage to find the array, but something still goes wrong along the way. The problem is that we use $b, which makes Perl think that we want a scalar and so it gives us a reference to the array instead of the array itself (which is not a scalar).
Aha! Of course! We must use
@b[0]
because @ tells Perl we want an array value. Not so. We get
ARRAY(0xb75eb0)
once again. I've never managed to understand why this is so and at this point I gave up on the entire thing.
Some weeks later I saw a helpful posting on no.perl: one should request a reference to the array, like this
@{$b[0]}
--------
You don't need to dereference the array to access an element of the nested array. All you need to do is:
say $b[0][1];
0.9
The reason $b[0] returns ARRAY(0xb75eb0) is the nested array is stored as a reference (references are sort of like pointers in Perl) in an element of the outer array but Perl automatically dereferences the nested array when you access an element of it. Now just like a pointer you can still directly access the reference to the nested array and deference it which is what '@{$b[0]}' does but it's not required.