in reply to Re: Perl variable scoping between functions
in thread Perl variable scoping between functions

Aha, That would be useful i guess. From another function I have been calling it this way. I am trying to put the file into an array which I can later make use of.
my @retarr = fLoadModules($modules);

Replies are listed 'Best First'.
Re^2: Perl variable scoping between functions
by hippo (Archbishop) on Jul 18, 2018 at 10:19 UTC

    Thanks. Your sub as written does not return anything so the @retarr array will be empty. You need to return a list like this:

    #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @retarr = (); print "At init " . Dumper (\@retarr); @retarr = void (); print "After void " . Dumper (\@retarr); @retarr = getlist (); print "After getlist " . Dumper (\@retarr); exit; sub void { # doesn't return anything } sub getlist { return (0, 1, 2); }

    That is an SSCCE. See also return. HTH.

      This is where an issue of scope gets raised in my head, how is it possible to return a value contained within the while loop and also return it from the sub which contains the while loop. I didn't think that it was possible.

        Your $module_id (which is what I take it your mean by "a value contained within the while loop") is declared inside the loop so scope ends when the loop ends. To retain those values push them onto something declared outside the loop.

        #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @retarr = (); print "At init " . Dumper (\@retarr); @retarr = void (); print "After void " . Dumper (\@retarr); @retarr = getlist (); print "After getlist " . Dumper (\@retarr); exit; sub void { # doesn't return anything } sub getlist { my @foo; while ($#foo < 2) { my $module_id = rand (); push @foo, $module_id; } return @foo; }