Ivan Bacher
Ivan Bacher

Reputation: 6154

perl: trouble passing array to function

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?

Upvotes: 1

Views: 139

Answers (3)

choroba
choroba

Reputation: 241808

If you turn on warnings, you will get the following one:

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

If you want to pass the referenced array by value, you have to dereference it:

@handOne = $cardFactory->createHand( @{ $Temp[0] } );

Upvotes: 4

mpapec
mpapec

Reputation: 50637

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;
}

Also take note that @temp[0] is array slice in case where scalar (array ref) is wanted, so it's better to state right intention:

@handOne = $cardFactory->createHand($temp[0]);

Upvotes: 2

isJustMe
isJustMe

Reputation: 5470

You are passing a reference instead of a value.

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

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

so in a nutshell change @temp[0] to $temp[0] when passing the argument

Upvotes: 1

Related Questions