in reply to In Search of a Smarter Sub
The first idea is to do what moritz suggested, but I see a small issue with that. Actually, it isn't so small.
While it appears to be that the only differences are that the colours in change, there are other pieces that are different. Here is a diff I ran just to see what was going on.
kschwind@yzerman:~/src/local/j.random> diff red.pl blue.pl 1,2c1,2 < if ($old_color eq "red") { < if ($_ == 11) { --- > if ($old_color eq "blue") { > if ($_ == 1) { 4c4 < } elsif ($button[$_+1]->cget(-background) eq "red") { --- > } elsif ($button[$_-1]->cget(-background) eq "blue") { 6c6 < } elsif ($_ <= 9 && $button[$_+1]->cget(-background) eq "blue" & +& $button[$_+2]->cget(-background) ne "white") { --- > } elsif ($_ >= 2 && $button[$_-1]->cget(-background) eq "red" && + $button[$_-2]->cget(-background) ne "white") { 8,9c8,9 < } elsif ($button[$_+1]->cget(-background) eq "white") { < make_color ("red", $_+1); --- > } elsif ($button[$_-1]->cget(-background) eq "white") { > make_color ("blue", $_-1); 13c13 < make_color ("red", $_+2); --- > make_color ("blue", $_-2);
So now it looks like we have some other differences. Mostly indexing from the looks of it. If you wanted to write some maintainable code, you may want to name these index variants into a hash of some type.
my smartish_sub { my ($colour) = @_; # Here is the hash with some constants based on the colour. You can +put this hash anywhere really. my %colour_indexes = ( red => ( equal_cond => 11, button_ind => 1, make_colour_ind1 => 1, make_colour_ind2 => 2, ), blue => ( equal_cond => 1, button_ind => -1, make_colour_ind1 => -1, make_colour_ind2 => -2, ) ); # rest of code is written to use the hash references keyed on the colo +ur, much like moritz described ...
The only other bit of mankery is that you have a <= 9 for red and >= 2 for blue. You may want to break that test out into another, smaller sub based on colour that will return true if that condition is met. It'll clean up the 'smart' sub and inlining it might get a bit messy.
|
|---|