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.

Six Sigma Certification
100% Online-Six Sigma Certificate from Villanova - Find Out More Now.

WinDev 11 - Powerful IDE
Develop 10 times faster ! ALM, IDE, .Net, RAD, 5GL, Database, 5GL, 64-bit, etc. Free Express version

Domain Name Registrations, Web Hosting, Email
Pay less for Domain Names, Increase your company's bottom line - get a raise. Accredited domain name registrar, ZippyNames.us : Discount bulk transfers, email, webhosting, dedicated servers. Earn money as a domain name reseller - better discounts!

Wanna see your ad here?