Now that everyone has thoroughly explained the how I shall explain the why.

Parameters that are passed to a subroutine are evaluated in list context and the resulting list is passed on to the subroutine, and when arrays are evaluated in a list context they are flattened to a list (the same is true of hashes). So when two arrays are passed to a subroutine, they are both evaluated in list context and flattened, resulting in a single list which is then passed onto a subroutine. To get around this we pass a reference to the subroutine instead, and since that is just a scalar it will not change in list context.

Here's some code to demonstrate the above paragraph

use strict; sub foo { print "got: ", join(', ', map { ref($_) ? "[@$_]" : $_ } @_),"\n"; } my @alpha = qw( a b c ); my @nums = qw( 1 2 3 ); # flattened array foo(@alpha); # 2 flattened arrays foo(@alpha, @nums); # array ref and flattened array foo(\@alpha, @nums); # flattened array and 2 array refs foo(@nums, \@alpha, [qw/d e f/]); # flattened array, an array ref and a list foo(@nums, [ qw/4 5 6/ ], qw/7 8 9/); __output__ got: a, b, c got: a, b, c, 1, 2, 3 got: [a b c], 1, 2, 3 got: 1, 2, 3, [a b c], [d e f] got: 1, 2, 3, [4 5 6], 7, 8, 9
So you can see there that the arrays are being flattened, lists are behaving normally and array refs work as expected.
HTH

_________
broquaint


In reply to Re: passing arrays to asubroutine by broquaint
in thread passing arrays to asubroutine by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.