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

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.
  • Comment on Re^3: Perl variable scoping between functions

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

    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; }