1

So all i want to do is pass a an array to a function (or subroutine) in PERL

So @Temp contains 2 arrays [0] = {xx,xx,xx,xx,xx} [1] = {xx,xx,xx,xx,xx}

#returns array containing two arrays

my @temp = $lineParser->parseLine($_);

@handOne = $cardFactory->createHand(@Temp[0]);
@handTwo = $cardFactory->createHand(@Temp[1]);

This is the createHand method wich is contained in a seperate class (or package or whatever)

sub createHand
{
    my $self = shift;
    my @temp = @_;
    my @arrayOfCards;
    foreach(@temp)
    {
        my $value = substr($_,0,1);
        my $color = substr($_,1,1);

        push(@arrayOfCards,new Card($value,$color));
    }

    return @arrayOfCards;
}

The problem i am having is that the array gets passed but is contains ARRAY(XXXXX) at the start of the array. E.g. {0 ARRAY(xxxxxx), 0 'xx', 1 'xx', ...}

Why does this happen?

How can I manage to do this correctly?

4

3 回答 3

4

如果你打开warnings,你会得到以下一个:

Scalar value @Temp[0] better written as $Temp[0]

如果要按值传递引用的数组,则必须取消引用它:

@handOne = $cardFactory->createHand( @{ $Temp[0] } );
于 2013-05-28T14:28:55.767 回答
2
sub createHand
{
    my $self = shift;
    my ($temp) = @_;
    my @arrayOfCards;
    foreach(@$temp)
    {
        my $value = substr($_,0,1);
        my $color = substr($_,1,1);

        push(@arrayOfCards,new Card($value,$color));
    }

    return @arrayOfCards;
}

另请注意,@temp[0] 是数组切片,以防需要标量(数组引用),因此最好说明正确的意图:

@handOne = $cardFactory->createHand($temp[0]);
于 2013-05-28T14:26:25.847 回答
1

您传递的是引用而不是值。

my @temp = $lineParser->parseLine($_);

@handOne = $cardFactory->createHand($Temp[0]);
@handTwo = $cardFactory->createHand($Temp[1]);

所以简而言之@temp[0]$temp[0]在传递参数时更改

于 2013-05-28T14:26:00.397 回答