If you specify -onClick, aren't you using the NEM?

At any rate, Steve was exactly right: I had to assign the name of the button
to a temp variable and use a closure. Thank you so much Steve!!! I could
have written your other post verbatim (I'm surprised I couldn't find it with
all my searching). I was banging my head against this for hours, losing the
will to live but knowing that it just HAD to be possible! Thanks again!

BTW, in case it helps anyone else, here's the updated code that DWIM:


foreach ( @button_names ) {
    my ($name) = $_; # This creates a closure and assigns the name to a
temporary variable that persists into the Button_Clicked() subroutine.
    $main->AddButton(
                   -name    => $name,
                   -size    => [251,35],
                   -pos     => [0,$y],
                   -text    => $name,
                   -onClick => sub { Button_Clicked ( $name ) },
    );
    ++$y;
}
 
sub Button_Clicked {
     print "Your name is " . $_[0];
}


Regards,
Rob

-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] 
Sent: Monday, January 08, 2007 4:08 AM
To: [EMAIL PROTECTED]; perl-win32-gui-users@lists.sourceforge.net
Subject: RE: [perl-win32-gui-users] How to pass $_ to a subroutine

Silly question, but why don't you use the NEM?

Cheers,

Jeremy.

-----Original Message-----
From: "Perl Rob" <[EMAIL PROTECTED]>
To: "Win32 GUI Users Mailing List"
<perl-win32-gui-users@lists.sourceforge.net>
Sent: 08/01/07 08:06
Subject: [perl-win32-gui-users] How to pass $_ to a subroutine

Hi all,
 
Are you ready for this one? :) Let's see if I can even explain what I'm
trying to do...
 
I'm attempting to dynamically create buttons that use the -onClick option to
go to a subroutine that is passed the name of the button. Why am I doing
this, you ask? Well, since I don't know the name of the button at the time
of its creation, I can't have an OEM event handler for it. Below is a code
snippet that might explain it better. The problem comes on line 7 when I try
to pass the name of the button (stored in $_ ) to the subroutine. I just
can't get $_ to persist when the subroutine is called later: 
 
#############################################
 
foreach ( @button_names ) {
    $main->AddButton(
                   -name    => $_,
                   -size    => [251,35],
                   -pos     => [0,$y],
                   -text    => $_,
                   -onClick => sub { Button_Clicked ( $_ ) },
    );
    ++$y;
}
 
sub Button_Clicked {
     print "Your name is " . $_;
}
 
#############################################
 
There just has to be a way to DWIM, but I've read perlsub over and over
again without figuring it out. How can I pass the name of the button to the
subroutine successfully?
 
Thanks,
Rob




Reply via email to