Get out early with Perl statement modifiers
Published in
3 min readJan 19, 2022
When I first started writing Perl in my early 20’s, I tended to follow a lot of the structured programming conventions I had learned in school through Pascal, especially the notion that every function has a single point of exit. For example:
sub double_even_number {
# not using signatures, this is mid-1990's code
my $number = shift; if (not $number % 2) {
$number *= 2;
} return $number;
}
This could get pretty convoluted, especially if I was doing something like validating multiple arguments. And at the time I didn’t yet grok how to handle exceptions with eval
and die
, so I’d end up with code like:
sub print_postal_address {
# too many arguments, I know
my ($name, $street1, $street2, $city, $state, $zip) = @_;
# also this notion of addresses is naive and US-centric my $error; if (!$name) {
$error = 'no name';
}
else {
print "$name\n"; if (!$street1) {
$error = 'no street';
}
else {
print "$street1\n"; if ($street2) {
print "$street2\n";
}