The Elite Noob has asked for the wisdom of the Perl Monks concerning the following question:

1. Return for arrays in Perl Ok first question. Say, you have this code.

... sub simpleTest{ ... my @i = qw(1 5 3 4 6 7); return @i; } my @test; @test = simpleTest();
Lets assume this code works and is bug free. Now, would the value of @test be @i? so if I showed @test, would I get 1 5 3 4 6 7?


1. Next, how do you get a recursive function to remember the value of a variable? so if you have this.

sub testFunc{ my $i = 0; $i++; testFunc(); }
In this code how do you get $i to keep increasing by one every time its called? so instead of this. 0 1 0 1 it prints 1 2 3 4 5 6 7 8 9. Thanks! For your help! I appreciate it!

Replies are listed 'Best First'.
Re: value of returned array, and remember variable in recursive function
by toolic (Bishop) on Mar 01, 2011 at 23:25 UTC
    so if I showed @test, would I get 1 5 3 4 6 7?
    All you have to do is print it to see:
    use warnings; use strict; use Data::Dumper; sub simpleTest { my @i = qw(1 5 3 4 6 7); return @i; } my @test; @test = simpleTest(); print '@test: ', Dumper(\@test); __END__ @test: $VAR1 = [ '1', '5', '3', '4', '6', '7' ];
    Outside of the sub, @i is undefined because of the scope.

    For recursion, you could use state:

    use warnings; use strict; use feature "state"; testFunc(); sub testFunc { state $i = 0; $i++; print "i=$i\n"; testFunc() if $i < 4; } __END__ i=1 i=2 i=3 i=4
    See also: How do I compose an effective node title?
      OMG, thanks helps out so much! :) It works!
Remembering the value of a variable
by ig (Vicar) on Mar 02, 2011 at 05:49 UTC

    To have a value persist between invocations of a subroutine, you can use a variable that exists outside the scope of the subroutine. There are various ways to do this, one of which is as follows. I added a limit on recursion.

    use strict; use warnings; testFunc(); { my $i = 0; sub testFunc { $i++; print "$i\n"; testFunc() if($i <10); } }