Developing
a Perl Routine
Randal L. Schwartz
I was cruising the Perl newsgroups the other day, and found the following
request. It appears to be a homework problem from a university assignment, so
I won't embarrass the original poster by including his name. (Normally, I try
to give credit to the source of inspiration for one of my columns, so if you
want your name in lights, please email your ideas to me!)
Here's the task: start with the three-letter English abbreviations for the
seven days of the week, in their natural order. Write a subroutine that takes
two of these weekday abbreviations, and returns a single comma-separated string
with all the days in between, wrapping around if necessary. For example, given
an input of Tue and Thu, the return value is Tue,Wed,Thu.
However, an input of Thu and Tue should wrap all the way around
to Thu,Fri,Sat,Sun,Mon,Tue. Be sure to reject (via die) any erroneous
inputs.
This doesn't sound like that difficult a task, but some interesting subtleties
arose as I was starting to solve it in my head. So, I'm writing this column
effectively in real time, as I would consider each piece of the problem, to
illustrate effective practices at developing Perl routines.
First, I need a subroutine name. This is sometimes harder than it looks. I
want a name that's short enough that I'll reuse it, but long enough to be descriptive
and unique. Let's start with day_string_range. Our initial
subroutine looks like:
sub day_string_range {
... code goes here ...
}
Good so far. I hope that wasn't too surprising. Next, I need to grab the start
and end values, so let's first check that they are there, and if so, grab them:
sub day_string_range {
die "too few args: @_" if @_ < 2;
die "too many args: @_" if @_ > 2;
my ($start,$end) = @_;
..
|