http://qs321.pair.com?node_id=766610

jpavel has asked for the wisdom of the Perl Monks concerning the following question:

Hello all! I actually don't have a problem with my code; I am, quite literally, seeking perl wisdom. I've used a similar bit of code in two different scripts to modify the default sub functions associated with variable Win32::GUI components. My first bit of code:
$comboboxes[$accountCount] = $main->AddCombobox( -name => $accountName."ComboBox", -top => $top, -left => $left, -width => 145, -height => 150, -tabstop => 1, -style => WS_VISIBLE | 3 | WS_VSCROLL ); foreach my $x (0..$accountCount){ $SUB = $accounts[$x]."ComboBox_Change"; *$SUB = sub { ComboBox $x }; }
That works fine. Porting it to my second script failed, though... the variable $j below gets passed as a reference instead of the value. That is to say, if I declared $j globally, everytime my sub got called, it had the global value. If it was local to the sub function, no value was passed. So, I ended up doing this:
$uniqueWindow[$i] = $main->AddTextfield( -height => 200, -width => $w-30, -background => [255,255,255], -top => $top, -left => 10, -text => "", -name => $i."Textfield", -align => left, -readonly => 1, -multiline => 1, -autovscroll => 1, -vscroll => 1, ); foreach my $j (0..$i-1) { $SUB = $j."Textfield_MaxText"; print "-->Assigning sub function for $j\n"; # Really?! Do I have to do this?! switch ($j) { case 0 {*$SUB = sub { variableMaxText(0); };} case 1 {*$SUB = sub { variableMaxText(1); };} case 2 {*$SUB = sub { variableMaxText(2); };} case 3 {*$SUB = sub { variableMaxText(3); };} case 4 {*$SUB = sub { variableMaxText(4); };} case 5 {*$SUB = sub { variableMaxText(5); };} case 6 {*$SUB = sub { variableMaxText(6); };} case 7 {*$SUB = sub { variableMaxText(7); };} case 8 {*$SUB = sub { variableMaxText(8); };} case 9 {*$SUB = sub { variableMaxText(9); };} case 10 {*$SUB = sub { variableMaxText(10); };} case 11 {*$SUB = sub { variableMaxText(11); };} } }
I don't plan on ever having more then 12 textfields, so it's functional, but the fact that it isn't truly variable bothers me. :-) Maybe I'm just too "Type A" or something. A key difference is probably the context: code snippet #1 occurs in the "main" section of the code, before any user interaction (before Win32::GUI::Dialog(), if you're familiar with the module). The second snippet exists in a sub function and is called during the course of user interaction. Hope I explained that adequately. I'm eager for an explanation!