Code in main vs subroutine
perl
Solution
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.
- If your subroutines are well-written (by which I mean that they don't use global variables, they have well-defined return points and they are small - certainly no more than a screen-full of code) then you can work on the code in the subroutine without caring about the rest of the code. And that makes your code easier to maintain.
- Well-named subroutines make your code easier to follow. If your main line of execution just calls half a dozen well-named subroutines then it is instantly obvious what your program does.
- Code in subroutines is far easier to test than code outside of subroutines. Even better if your subroutines are in a separate library. The test suite can just load the library and try each of the subroutines in turn, checking that it has the correct effect.
These points are obviously all simplifications. But they go some way towards explaining why the vast majority of my code is in subroutines.
Problem
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!