in reply to Perl variable scoping between functions

I guess you want something like this…

sub fLoadModules { my ($modules) = @_; my @stuff_to_return; open my $fh, "<", $modules or die "Couldn't open module file: $mod +ules"; while(<$fh>) { chomp; my ($module_id) = split /;/; print Dumper($module_id); push @stuff_to_return, $module_id; } close $fh; return @stuff_to_return; }

Replies are listed 'Best First'.
Re^2: Perl variable scoping between functions
by Bryan882 (Novice) on Jul 18, 2018 at 11:07 UTC
    True, you can always return an array but I have been unsuccessful thusfar in calling the sub containing the array. For clarity I have posted the way in which I attempt to call the sub.
    ##MAIN my $modules_path = $opts{e}; my $modules = fLoadModules $modules_path; sub Other { my @other = fLoadModules(); }
      The variable $modules declared in MAIN is shadowed by the lexical $modules declared inside the function. To properly pass parameters to @_, put them into the parameter list:
      my @other = fLoadModules($modules);

      @other will be empty, as fLoadModules doesn't return anything, but that's already been covered in other replies.

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
        Okay, But attempting the call this way will result in the file opening handle to be replaced with the count of the array.
        sub fLoadModules { my ($modules) = @_; my @array; open my $fh, "<", $modules or die "Couldn't open module file: $mod +ules"; while(<$fh>) { chomp; my ($module_id) = split /;/; push @array, $module_id; } close $fh; return @array; }
        In the scope of this, when you call the sub via  my @other = fLoadModules($modules); it will try to open the array count instead of the file. This had come up in my previous investigation/testing before I turned to the good people of perl monks for answers.