Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 2001 > August 2001

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) = @_;
 ..

				  



MarketPlace

Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.

Workflow Enabled Help Desk & IT Service Management
Automate service desk activities and integrate processes across IT. Learn more here.

Flowcharts from C/C++ code -- Free trial download
Understand C/C++ code in less time. A new team member ? Inherited legacy code ? Get up to speed faster with Crystal Flow for C/C++. Code-formatting improves readability. Flowcharts are integrated with code browser. Export flowcharts to Visio.

Discover WinDev 11 RAD
and develop 10 times faster ! ALM, IDE, .Net, PDF, 5GL, Database, 64-bit, etc. Free Express version

Wanna see your ad here?