Sachin_dada has asked for the wisdom of the Perl Monks concerning the following question:

Hi All, I have a doubt in my code. I'm using subroutine, where once i call it, i'm storing those values another array variable & read each using Foreach loop. But i'm getting only the first value of the array, by using forreach loop. Could some please correct by code.

#!/usr/bin/perl -w use strict; sub job { @row= {AAA,BBB}; return @row; } my @red =job(); foreach my $r(@red) { print $r; }

Could someone please correct where i'm conceptually wrong. Its just returning 'AAA' as output, instead of returning both.

Replies are listed 'Best First'.
Re: Subroutine - Return Array
by davido (Cardinal) on Nov 11, 2010 at 06:01 UTC

    Line by line...

    @row= {AAA,BBB};

    You probably mean to say,

    @row = ( 'AAA', 'BBB' );

    Or...

    @row = qw/AAA BBB/;

    But you ought to be limiting scope, and in fact, strict is going to require that you do so. Thus....

    sub job { my @row = qw/AAA BBB/; return @row }

    Dave

      But you ought to be limiting scope, and in fact, strict is going to require that you do so.
      No, it doesn't.
Re: Subroutine - Return Array
by suhailck (Friar) on Nov 11, 2010 at 05:45 UTC
    Your posted code produces errors and warnings.
    I think you are not clear about declaring array in Perl, see perldata

    Here is the corrected code
    #!/usr/bin/perl -w use strict; sub job { my @row= ('AAA','BBB'); # or my @row = qw(AAA BBB); return @row; } my @red =job(); foreach my $r(@red) { print $r; }
Re: Subroutine - Return Array
by PeterPeiGuo (Hermit) on Nov 11, 2010 at 06:07 UTC

    You said that you only saw "AAA" as output. That's interesting, as your porgram cannot even run as it is.

    Other than some of the obvious problems. It is usually a good idea to return array ref instead of array.

    use strict; sub job { my $row= ["AAA","BBB"]; return $row; } my $red =job(); foreach my $r(@$red) { print $r, "\n"; }

    Peter (Guo) Pei