SWITCH: {
if (foo) {
do something
last SWITCH;
}
if (bar) {
do something
last SWITCH;
}
if (baz) {
do something
last SWITCH;
}
last SWITCH;
}
And, I tell them over and over that this really isn't what labels are for. I even tell them that it causes Perl to needlessly keep track of more things, and show them some examples of when a label may make better sense, like:
FOO: for my $foo (@bar) {
blah blah
BAR: for my $bar (@baz) {
if (something) {
next FOO;
}else{
next BAR;
}
}
or
FOO: { something }
BAR: { something }
BAZ: { something }
if (foo) {
goto FOO;
} elsif (bar) {
goto BAR;
} else {
goto BAZ;
}
Basically, using them in a way which isn't simply adding a useless label around a simple block of conditionals.
Am I crazy in my advice here? Is there any other way I could convince people that this just isn't the best programming practice and not just a pet peeve? This is all througout the codebase. A script may have 5 of these (or more) and use multiple modules which also have many of them, etc.. HELP!
Dealing With Co-Workers (Score:1)
-biz-
Aack! That's ugly (Score:2)
No, I wouldn't use a switch-like construct there. What's the point of a label when there's a much cleaner solution? I would probably use a dispatch table like the following:
my %dispatch = (
foo => \&foo,
bar => \&bar,
baz => \&baz
);
#later
if ( exists $dispatch{$function} ) {
$dispatch{function}->(@args);
}
else {
die "No such function ($function)";
}
I don't know, maybe it's just me, but that seems much cleaner and
Re:Aack! That's ugly (Score:2)
Re:Aack! That's ugly (Score:2)
I humbly submit an example of when SWITCH can go horribly wrong. The temptation to use labels for control flow when they are not required makes bugs like this more likely.
while ( my $data = $t_sth->fetchrow_arrayref ) { /= PRECISION;
my ( $amt, $id ) = @$data;
$amt
SWITCH: {
$id == $CASH && ($tcash += $amt) && last SWITCH;
$id == $ACCOUNT
Re:Aack! That's ugly (Score:2)
Maybe I can turn this into a "THAT IS FIRE, DO NOT TOUCH THE FIRE" ;-)
Re:Aack! That's ugly (Score:2)
I saw the "bug" when I saw the code, but then I thought "the programmer wouldn't have used that construct if ($tcash += $amt) could ever yield zero!".
I like pie.