Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Binding within a sub

by Eily (Monsignor)
on Apr 18, 2018 at 08:04 UTC ( #1213107=note: print w/replies, xml ) Need Help??

in reply to Binding within a sub

To me it looks like you have a scope problem, because your code contains closures and I'm pretty sure that this is not intended. A closure is a subroutine that keeps access to a lexical (my) variable that it uses but that is declared somewhere else. For example, your first bind sub uses the variable $text which is declared in the for loop. In each iteration of the loop, the variable is the same (it's not a new $text) and only its value is changed, so all your bind sub actually will keep access to the same $text, meaning they may potentially (and probably) read the same value when called. To avoid this problem, you can create a new variable in each iteration of the loop, so that it isn't shared:

for my $text ( qw( one two three four five six seven eight nine ten ) +) { my $uniq_text = $text; # Copy ... # Your code, where $uniq_text is a new variable that was never u +sed before, and noone else has access to. }

The other issue I see is $panel and $selectedtext which aren't declared anywhere in your example, so I don't know if they are lexicals (my) or package variables (do you use strict?) but in all cases they are shared among all the bind subs, and again I don't know if this is by design or mistake.

And I'm not sure about why you would define @items outside of your InitializeList sub, I suppose it is because you want to read its content after the call? If that's the case, maybe you can return it from the sub, rather handle the same variable in different places:

sub InitializeList { my @items; # no need to undef it for my $text ( qw( one two three four five six seven eight nine ten +) ) ... return @items; } my @res = InitializeList(); # get the items from that call

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2021-02-25 00:20 GMT
Find Nodes?
    Voting Booth?

    No recent polls found