swaroop.m has asked for the wisdom of the Perl Monks concerning the following question:

Hi
i need to pass two arrays as function params .i use the following code.The below code gives me the reference to array but how do i acccess the data
#!/usr/bin/perl -w use strict; my @arrTest = (1,2,3); my @arrTest2 = (4,5,6); &GetData (\@arrTest , \@arrTest2 ); sub GetData { my ($messages, $count) = @_; # print the count; foreach (@ {$messages}) { print "$_! \n"; } # print the count; foreach (@ {$count}) { print "$_! \n"; } }

Edit: code tags (davorg)

Replies are listed 'Best First'.
Re: Help Pass array as function params
by davorg (Chancellor) on Aug 19, 2004 at 09:24 UTC
    #!/usr/bin/perl -w use strict; my @arrTest = (1,2,3); my @arrTest2 = (4,5,6); &GetData (\@arrTest , \@arrTest2 ); sub GetData { my ($messages, $count) = @_; # print the count; foreach (@ {$messages}) { print "$_! \n"; } # print the count; foreach (@ {$count}) { print "$_! \n"; } }

    You had too many levels of references.

    Update: OK, now I'm confused. When I answered this post the code looked like this:

    my @arrTest = 1,2,3;
    my @arrTest2 = 4,5,6;

    Which, given the way that Perlmonks works, I interpreted as:

    my @arrTest = [1,2,3]; my @arrTest2 = [4,5,6];

    Hence, my remark about too many levels of references.

    Now the code has been "fixed" and it looks identical to the fixes that I suggested. Which means it works and I look like I've wasted my time. Which is perhaps why someone has downvoted this node.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Help Pass array as function params
by NetWallah (Canon) on Aug 19, 2004 at 13:20 UTC
    You could shorten the code (Save keystrokes) by replacing
    foreach (@ {$count}) { print "$_! \n"; }
    with
    print "$_! \n" for @$count;
    If you are just getting started with Array references the link to "Converting an Array Reference into an Array" may provide enlightenmet.

        Earth first! (We'll rob the other planets later)

Re: Help Pass array as function params
by ikegami (Patriarch) on Aug 19, 2004 at 17:24 UTC

    basically, replace arrTest with {$messages}, so:

    @{$messages} for @arrTest (the whole array). ${$messages}[$i] for $arrTest[$i] (an element). @{$messages}{0, 2} for @arrTest{0, 2} (a slice). $#{$messages} for $#arrTest (the last index).

    The curly brackets are optional, btw.