2009/12/11 Bryan R Harris <bryan_r_har...@raytheon.com>:
> I'm not even sure how to ask this question, but here goes:
>
> I struggle knowing how to structure my code, what things belong as their own
> subroutines and what things can stay in the main script.  How do the smart
> guys make these decisions?
>
> For example, let's say I need to:
>
> 1.  Read a complex file
> 2.  Populate a complex dataset
> 3.  Accept user input
> 4.  Based on user input, either modify or add to dataset, or quit
> 5.  Update files on disk
> 6.  Go to step #3
>
> Which steps should be their own subroutines vs. just writing them into the
> main part of the script?  And how did you make that decision?

If you like, put everything in its own subroutine, call the main one
"main", and reduce the main part of your script to just this:

main();

If you want a more OO-style script, you might have:

my $x = Myprogram->new();
$x->main();

> Seems like a waste to do step 2 in a subroutine since we only do it once,
> but it does fill the main body of the script with code-noise that makes it
> harder to debug overall logic problems...  Not much logic here, but
> certainly in more complex scripts.

A waste of what exactly? You don't have a limited budget of "sub" keywords.

Subroutines are not just about code reuse. Which is more readable:

my $x = [
  # Big complex data structure
  # ...
  # ...
  # ...
  # ...
];

my $y = [
  # Big complex data structure
  # ...
  # ...
  # ...
  # ...
];

for my $p ($x) {
  for my $q ($y) {
    #Big
    # complex
    # multi-statement
    # manipulation
    # of
    # $p
    # and
    # $q
  }
}

Or this:

my $x = populate_x();
my $y = populate_y();
for my $p (@$x) {
   for my $q (@$y) {
      process_pq($p, $q);
   }
}

Or even:
my $x = populate_x();
my $y = populate_y();
process_xy($x, $y); # xy_process now contains the for loops

The point is that in the first version, you are constantly bouncing
from the big-picture ideas to the low-level messy details. By
abstracting code out into subroutines populate_x(), populate_y() and
process_xy(), you have the main script which deals in big ideas, and
three subroutines which deal with messy details. A subroutine should
do one thing, and do it well.

> Any suggestions?  Where can I read more on this stuff?  What questions
> should I be asking that I'm not smart enough to ask?

The best that I can suggest is to read other people's code and ask
other people to read your code. Think of a specific example and come
up with a plan of how you would code it, and ask for criticism.

Phil

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to