Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: Perl variable scoping between functions

by Bryan882 (Novice)
on Jul 18, 2018 at 11:07 UTC ( [id://1218736]=note: print w/replies, xml ) Need Help??


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

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

Replies are listed 'Best First'.
Re^3: Perl variable scoping between functions
by choroba (Cardinal) on Jul 18, 2018 at 11:34 UTC
    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.

        Have you tested fLoadModules in isolation, by passing it a hardcoded string?

        I think the original problem comes from this line, which assigns $modules the number of found modules:

        my $modules = fLoadModules $modules_path;

        If you want to receive a list back instead of the number of modules, you need to have a list on the left hand side of the assignment:

        my @modules = fLoadModules $modules_path;
Re^3: Perl variable scoping between functions
by tobyink (Canon) on Jul 18, 2018 at 12:56 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1218736]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (9)
As of 2024-04-23 21:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found