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?

1
  • Is that a typo, or do you have two variables named @temp and @Temp. Because they are two different variables. Commented May 28, 2013 at 16:00

3 Answers 3

4

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] } );
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, seemed to fix to problem i was having.
WOuld you be able to explain what @{ $Temp[0] } means?
Strictly speaking @{ $Temp[0] } doesn't pass an array :)
@686: $Temp[0] is an array reference. To dereference it, you have to use the dereference operator @{ ... }.
alright cool thx for the reply this is the first thing i have coding in perl =D
|
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;
}

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]);

2 Comments

You have two options, passing an array or list of values to function. Above example passes an array as you stated in question subject.
@{ $Temp[0] } solved my problem and $Temp[0] doesnt seem to be working
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.