@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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |