Your variables do not contain what you think they do; after assignment:

@lsList == ("Hello","World","BANG!","2","!") $sItem == 5 $nItem == 5

@_ contains the entire argument list. This means you assign the entire argument list to @lsList and then repeat the assignment in scalar context, which assigns the length of the array (5) to your two scalars.

If you want to pass an array into a subroutine, likely the easiest way to do it is with an array reference (see perlreftut). Your code might then look like:

#!/usr/bin/perl use strict; use warnings; my @hello = ("Hello", "World", "BANG!"); sub ListInsert { my ($lsList_ref, $sItem, $nItem) = @_; my @lsList = @$lsList_ref; splice(@lsList, $nItem, 0, $sItem); print "@lsList\n"; } ListInsert(\@hello, "!", 2);

Note I also reversed "!" and 2 in your argument list, since you had that backwards. Also note that I dereferenced the array before the splice to avoid affecting @hello. If you mean to change @hello, then you would need something more like:

#!/usr/bin/perl use strict; use warnings; my @hello = ("Hello", "World", "BANG!"); sub ListInsert { my ($lsList_ref, $sItem, $nItem) = @_; splice(@$lsList_ref, $nItem, 0, $sItem); my @lsList = @$lsList_ref; print "@lsList\n"; } ListInsert(\@hello, "!", 2);

In reply to Re: Passing arrays in subs by kennethk
in thread Passing arrays in subs by speedyshady

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.