how do you decide whether to put code in a subroutine or in main portion of a Perl script?
I understand if you need to re-use code you would put it in subroutine, but what if you’re not reusing? Is it good practice to put in subroutines to group code and make it easier to read?
Example (in main):
my ($num_one, $num_two) = 1, 2;
print $num_one + $num_two;
print $num_one - $num_two;
Example (in subroutines):
my ($num_one, $num_two) = 1, 2;
add($num_one, $num_two);
subtract($num_one, $num_two);
sub add {
my ($num_one, $num_two) = @_;
return $num_one + $num_two;
}
sub subtract {
my ($num_one, $num_two) = @_;
return $num_one - $num_two;
}
I know this is a simple example, but for more complex code (if sub add and sub subtract had more code), would it make sense to group in subroutines?
Thanks!
You’ve pointed out that code is easier to reuse if it’s in a subroutine. I think there are at least three other good reasons for using subroutines.
These points are obviously all simplifications. But they go some way towards explaining why the vast majority of my code is in subroutines.