Henry
Henry

Reputation: 33

Structuring fairly small scripts

I write alot of fairly small perl scripts. They will range from 10 lines to maybe 1,000 lines but the median size is probably only around 100 lines. When I start writing the script I tend to break things up into chunks and create subroutines. What happens is I end up writing alot of scripts that look something like

sub mkdir {
    ... directory testing logic ...
    ... mkdir ...
}
sub createFile {
    ... check for directory ...
    ... try and create the file, exit if failure ...
}
sub somethingElse {
    .... do stuff with the file that was created ...
}
sub yetAnotherThing {
    ... do even more stuff ...
}

&mkdir;
&createFile;
&somethingElse
&yetAnotherThing

This has always looked very odd to me. I like that it ends up being modular and I can easily comment out certain tasks but I'm not certain it's the best way to structure such small programs.

My questions are:

  1. Does anyone have any specific reason why I shouldn't structure scripts in this manner? I don't see many other people doing this so it feels like perhaps I'm doing something wrong.
  2. Can anyone suggest a better way to structure smaller scripts? Should I just skip creating subroutines at all and write out what I want my script to do in order? Am I overthinking this? :)

Thank you!

Upvotes: 3

Views: 102

Answers (2)

Neil Slater
Neil Slater

Reputation: 27207

Your approach looks sensible enough to me, and I do see scripts like it elsewhere.

Some of your approach might now be a comfortable habit that you have grown into and would deserve a re-think and a deliberate try for something higher level. For a start, how many of your scripts contain pretty much the same 5 directory and file-handling logic subroutines? There's a good chance you could either:

  • Make a concerted effort to find a CPAN module that would make those routines shorter or not required.

  • Write your own modules to contain code shared between your scripts.

Both these things will allow you to become more efficient, and as you seem to be writing a lot of these scripts, that's worth pursuing.

Upvotes: 2

slebetman
slebetman

Reputation: 113964

What you're doing is correct and it's considered good practice in programming. It's called functional decomposition - you break down your tasks into smaller functions.

In fact, in the industry what tends to happen is people start out writing large chunks of inline code and then later when that becomes unmanageable start to refactor out the code to become more like what you're doing.

Look at projects in CPAN for example. Most of them are broken down to small functions. In fact, most of them are further broken down into modules of related functions.

This is a good first step. The next step is to write .pm files of related functions that you can use in your code. Next step after that is to write object oriented code.

Upvotes: 3

Related Questions