in reply to Push array into array of arrays

push(@a,pop(@myArrofArray));
print @a, I got ARRAY(0x858bd8)

expected output: @a = ('x', 'y', 'z', 8,9,7);
Can anyone point out the mistake?

A Perl 2D array is array of references to arrays. Above, you pop an array ref off of @myArrofArray and then push that array ref onto @a. So @a will contain a single element, a single scalar array reference.

Consider:

my $array_ref = pop @myArrofArray; print "@$array_ref\n"; #dereference the reference push @a, @$array_ref; print "@a\n"; #now @a contains the entire row of values
To print the values of a "row" in a 2D array, you have to "dereference" the reference.

PS: the "@a" and "@b" have special meanings within Perl, it is best to use x,y or something else.

Update: I got a few comments about not using @a or @b. My advice was an oversimplification. $a and $b have special meanings within Perl. It is completely allowed to use @a or %a - these do not have a special meaning. However I avoid those variables and recommend that others do the same. Leave the vars names a and b to Perl. This is to avoid any confusion. I guess you can have $a[0] which is first element of @a and that might be confused with $a which is completely different.

Replies are listed 'Best First'.
Re^2: Push array into array of arrays
by hippo (Archbishop) on Dec 18, 2018 at 23:02 UTC
    PS: the "@a" and "@b" have special meanings within Perl

    That's the first I've heard of this. What are the special meanings of @a and @b?

Re^2: Push array into array of arrays
by learnedbyerror (Monk) on Dec 19, 2018 at 13:03 UTC

    I don't think there are special meanings for "@a" and "@b", I think you may be thinking about "$a" and "$b" which are identified as special variable for use in perl sort, see perlvar. perlcritic will create a message "Magic variable "@a" should be assigned as "local" at line..."; however, I am not aware of and cannot find any reference to "@a" or "@b" as being a magic variable

    Please explain if I am missing something!

    Cheers, lbe

      Hi Ibe,
      You have this completely right!

      My advice was over simplified.
      In Perl, the various sigils (example: %,$,@) have their own namespaces.

      Yes, it is possible to have @x and $x or even %x to be distinct things.
      $a is different than @a.

      I do not believe that using the same alphanumeric name for a hash, array or scalar is a good idea.
      Not everything that is allowed by Perl is "good idea".

      I recommend and advise avoiding using "a" or "b" for any kind of user variable.
      Consider $a[1] -- that accesses @a instead of the $a scalar. This can be confusing.

      I stand by my recommendation to avoid any user variable named "a" or "b" or using the same string to define things like: %xyz, $xyz, @xyz.
      Use different names for these very different things.