develooper Front page | perl.beginners | Postings from July 2006

Re: Multidimensional array / Passing an array to a sub

Thread Previous | Thread Next
From:
John W. Krahn
Date:
July 30, 2006 03:03
Subject:
Re: Multidimensional array / Passing an array to a sub
Message ID:
44CC83D8.5030105@telus.net
Martin Tournoij wrote:
> I'm currently massivly confused by multidimensional arrays and passing 
> arrays to subs.
> 
> Why is it that @_[1] isn't properly copied to @a?
> 
> I'm not sure what exactly I'm doing wrong here, probably something
> simple,  but I can't find anything that works in the manpages or on the
> site...
> 
> Music($var1, \@array);
> 
> sub Music
> {
>   print $_[1][1];  # works

$_[1] contains a reference to @array so $_[1][1] is the same as $array[1] (or
the second element of @array.)


>   my @a = @_[1] # Gives warning, should be written as $_[1]

@_[1] is an array slice, the warning is because the list [1] has only one
element, it's the same as saying "$a[0] = @_[1]".  If you want to copy @array
to @a then you have to dereference it properly:

my @a = @{ $_[1] }

But if you are going to copy the array anyway you could just do it like this:

Music($var1, @array);

sub Music
{
my ( $var, @a ) = @_;




John
-- 
use Perl;
program
fulfillment

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About