Get out early with Perl statement modifiers

Mark Gardner
CodeX
Published in
3 min readJan 19, 2022

--

Photo by Pixabay on Pexels.com

When I first start­ed writ­ing Perl in my ear­ly 20’s, I tend­ed to fol­low a lot of the struc­tured pro­gram­ming con­ven­tions I had learned in school through Pascal, espe­cial­ly the notion that every func­tion has a sin­gle 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 pret­ty con­vo­lut­ed, espe­cial­ly if I was doing some­thing like val­i­dat­ing mul­ti­ple argu­ments. And at the time I didn’t yet grok how to han­dle excep­tions 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";
}

--

--