Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Global vs. local?

by Corion (Patriarch)
on May 28, 2009 at 09:24 UTC ( [id://766613]=note: print w/replies, xml ) Need Help??


in reply to Global vs. local?

switch ($j) {

Whoa! Don't.

This code suggests to me that you're using Switch, which is known to introduce random and weird errors into your scripts. The first step is to remove everything related to Switch.

After you've exorcised all usage of Switch from your script, your usage should basically work. Potentially, you need to declare another variable and store the index in it rather than the loop variable:

foreach my $j (0..$i-1) { my $idx = $j; # make a copy my $SUB = "${idx}Textfield_MaxText"; *$SUB = sub { variableMaxText( $idx ); };

Replies are listed 'Best First'.
Re^2: Global vs. local?
by moritz (Cardinal) on May 28, 2009 at 09:32 UTC
    Whoa! Don't.

    If you tell people what not to use, also tell them what to use instead ;-)

    here: perl 5.10 introduces given/when, see perl5100delta. Short example:

    use 5.010; given ($value) { when (1) { ... } when (2) { ... } default { die "Don't know what to do with '$_'" } }

    It's not needed here, because a closure is much better, but in general it's surely good to know.

      Thanks, I'll make that change!
Re^2: Global vs. local?
by jpavel (Sexton) on May 28, 2009 at 09:46 UTC
    This did it! Thanks. I'm not entirely sure why this was necessary, when the first snippet worked taking $x from the for loop? I guess there is something about variable reference that I don't understand going on.

      I have no explanation for the failure. I tried to replicate your behavior with 5.8.8 and 5.10.0 but my tests worked in every case I tried. My last test program was:

      #use strict; use warnings; sub subfunction { foreach my $j (0..5) { my $SUB = 'testsub'.$j; *$SUB = sub { display($j); }; } } sub display { my $x = shift; print "\$x = $x\n"; } subfunction(); &testsub0(); &testsub1(); &testsub2(); &testsub3(); &testsub4(); &testsub5(); __END__ $x = 0 $x = 1 $x = 2 $x = 3 $x = 4 $x = 5

      Can you post a minimal running test script that demonstrates the bug unexpected behavior?

      What version of perl and what platform?

        ActiveState perl 5.10.0 (Binary build 1004 287188)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-19 11:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found