How can I relate to this array of Perl arrays?

Consider this Perl Code

my @a=[[1]]; print $a[0][0]; **output** ARRAY(0x229e8) 

Why does it print ARRAY instead of 1 ? I would expect @a create an array of size 1 with reference to the second array containing only one element, 1 .

+4
source share
4 answers

It's complicated. You have designated @a as a list containing an array reference containing an array reference, which is another additional level of indirection than you expected.

To get the expected results, you had to say

 @a = ( [ 1 ] ); 
+14
source

The value you want is in $a[0][0][0] . You assign an array reference as the first element of the @a array.

This is a similar thing:

 my @a = 'scalar'; 

And this will create an array of 1 slot with the string 'scalar' as the only element. Therefore, when you assign a scalar to an array, Perl tries to make it look like you want and create a list of size 1 with a scalar value as the first element.

Moreover,

 my @a = undef; 

does the same, but the first undef slot. Do you want to

 my @a = [1]; 
+11
source

Here is what I assume you wanted to write:

 my $x = [[1]]; # reference to anon array containing # reference to anon array with one element print $x->[0][0]; 

See also Perl Data Structures Cookbook .

+4
source

mobrule, Axeman and Sinan answered your question: you created a data structure 3 layers deep, not 2.

I am surprised that no one suggested using the core Data :: Dumper library to help understand data structure issues.

 use Data::Dumper; my @a = [[1]]; print Dumper \@a; 

Fingerprints:

$ VAR1 = [[[1]]];

Your error used the array reference constructor [] instead of using parentheses (or nothing). @a = ([1]);

So why does Perl have weird syntax [] and {} for declaring hash links and array references?

It comes down to Perl aligning lists. This means that if you say: @a = (@b, @c); that @a assigned the contents of @b , concatenated by the contents of @c . This is the same as the Python extend list method. If you want @a have two elements, you need to make them not expand. You do this by taking a reference to each array: @a = (\@b, \@c); . This is similar to the Python append list method.

If you want to create anonymous nested structures, you need to specify them as hashes or arrays. What is where the syntax mentioned above comes in.

But what is the use of the list? Why is it worth using this unusual syntax to create arrays and hash links that is different from the syntax used for normal initialization?

Smoothing the list means that you can easily compile a list of subroutine parameters in a variable and then pass them without doing anything complicated: foo(@some_args, 5, @more_args); . See Apply on wikipedia for information on how this concept works in other languages. You can do all sorts of other nice things with map and other functions.

+3
source

Source: https://habr.com/ru/post/1311125/


All Articles