jmlynesjr has asked for the wisdom of the Perl Monks concerning the following question:
Monks:
In cleaning up my More wxPerl Examples code in preparation to moving it to github, I came across several examples that use the switch construct. I want to update these to use the given-when construct. As seen below, I got a version to work, but there has to be a simpler/cleaner syntax. It seems to be something to do with (de)referencing the constant.
Thanks in advance, James
wxID_YES, wxID_NO, and wxID_CANCEL are wxPerl constants from use Wx qw(:everything).
Original working construct
use switch; switch ($selection) { case wxID_YES {$self->Wx::LogStatus ("You pressed: \ +"Yes\" ")} case wxID_NO {$self->Wx::LogStatus ("You pressed: \" +No\" ")} case wxID_CANCEL {$self->Wx::LogStatus ("You pressed: \" +Cancel\" ")} }
Replaced switch construct with given-when construct - fails, always takes Yes path
given ($selection) { when (wxID_YES) {$self->Wx::LogStatus ("You pressed: + \"Yes\" ")} when (wxID_NO) {$self->Wx::LogStatus ("You pressed: +\"No\" ")} when (wxID_CANCEL) {$self->Wx::LogStatus ("You pressed: +\"Cancel\" ")} }
Working given-when construct
given ($selection) { when ($_ == wxID_YES) {$self->Wx::LogStatus ("You pre +ssed: \"Yes\" ")} when ($_ == wxID_NO) {$self->Wx::LogStatus ("You pres +sed: \"No\" ")} when ($_ == wxID_CANCEL) {$self->Wx::LogStatus ("You pres +sed: \"Cancel\" ")} }
It also works if the constant is assigned to a scaler and then the scaler is used in the when clause.
Update1:my $yes = wxID_YES; when ($yes) {....}
Thanks to Athanasius for the great explanation and test code. I had seen the constant as subroutine construct, but didn't know how it worked in this case(hidden smart match). Thanks also to tobyink. The when ([wxID_YES]) {....} also works (why?) and seems cleaner than what I had come up with. I will go with the bracket construct. Thanks also to Anonymous Monk for the reference to the bug report.
Update2:Thanks again to Athanasius and tobyink. The "why?" is now answered very clearly. I had tried when ((wxID_YES)) and when ({wxID_YES}). I guess one more try and I wouldn't have asked the question and I still wouldn't have known why it worked! There are a lot of good teachers out there willing to share their time and knowledge. Thanks!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: converting from switch to given-when
by Athanasius (Archbishop) on Sep 25, 2012 at 03:03 UTC | |
by tobyink (Canon) on Sep 25, 2012 at 06:05 UTC | |
by Anonymous Monk on Sep 25, 2012 at 07:48 UTC | |
|
Re: converting from switch to given-when
by tobyink (Canon) on Sep 25, 2012 at 06:07 UTC | |
by tobyink (Canon) on Sep 25, 2012 at 06:26 UTC | |
|
Re: converting from switch to given-when
by Athanasius (Archbishop) on Sep 26, 2012 at 08:07 UTC | |
by tobyink (Canon) on Sep 26, 2012 at 08:48 UTC |