Reputation: 1241
I wonder how to leave a switch case element from a subroutine like this:
#!/usr/bin/perl
use Switch;
switch ($command) {
case 'create_vmr' {
... do something ...
callsub($blabla);
... do something more ...
}
case 'delete_vmr' {
... do something ...
callsub($blabla);
... do something more ...
}
}
... final code ...
exit(0);
sub callsub {
... check something ...
last if $condition;
}
My thought was, that 'last' in callsub() will exit the case it was called from, so that the code will proceed after the switch elemeent. But this does not work. 'last' works fine if I call it in the case element directly.
So, how can I leave the switch element from a sub?
edit: And I don't want to use 'goto' please ;)
Upvotes: 0
Views: 643
Reputation: 35208
I would recommend not trying to obfuscate your program flow by hiding breaks.
Instead, make the subroutines return a true value if it succeeds, and break from the calling code block.
In this instance, I would recommend using a dispatch table instead of the deprecated Switch module. The following should demonstrate:
use strict;
use warnings;
my %dispatch = (
create_vmr => sub {
# ... do something ...
callsub('foo') or return;
# ... do something more ...
},
delete_vmr => sub {
# ... do something ...
callsub('bar') or return;
# ... do something more ...
},
);
my $command = 'delete_vmr';
if ( $dispatch{$command} ) {
$dispatch{$command}();
} else {
warn "Unrecognized $command";
}
exit(0);
sub callsub {
# ... check something ...
return $_[0] eq 'foo';
}
Upvotes: 3