Saturday, December 20, 2008

Timing is everything

My file synchroniser needs to know when a file was last modified, in order to decide if this version is newer than the version it's being compared with. Perl provides a very convenient stat() function that includes this, along with a variety of other information.

All we need do is...

use File::stat;

then...

my $StatusBlock = stat($Entry)
or die "Couldn't stat $Entry: $!";
my $LastModified = $StatusBlock->mtime;
print MASTERFILE "$Entry | $LastModified\n";

The first line creates a hash for the file information, the second is a crude handler for any errors, the third extracts the number of seconds since the epoch at which the file was modified and the last prints the file name and the date to my work file.

This is a nice example of Perl's power to simplify something that would otherwise require a lot of code. What's more, it's easy to understand, which is a massive advantage when maintenance is required. Having spent far too long puzzling over obscure code in the wee small hours with frantic managers breathing heavily in my ear, 'easy to understand' seems very good to me.
:

Friday, December 19, 2008

Progress in Perl

I always find 'silent' programmes especially irritating. There's nothing worse than starting a process and then watching a frozen screen in the hope of seeing some sign of progress. This is especially irritating with CLI programmes - you just don't know if it's busy, crashed or plain confused.

I've been working on a directory synchroniser recently and this very issue, of letting the user know that something is happening, came up. There are all sorts of ways to solve it. Simple but inelegant solutions include filling the screen with lines of detail showing what's going on, printing a single dot for each pass through the programme's loop, even writing a copious log and sneeringly advising the user to tail -f the file. Then there are the pretty, but complicated solutions, all of which tend to be a variation on the progress bar theme. Beside taking a lot of effort, these tend to impose a significant run-time overhead and, for a simple little job such as my synchroniser project, seem like massive overkill.

There is, however, one very neat and simple CLI solution: use a spinner. Although GUI spinners can be complicated, in text mode Perl, they are almost laughably trivial, although I don't recall seeing this approach described anywhere. The slight spin (ouch!) on my approach, is that I needed the progress to be shown in a sub-routine that calls itself recursively, but that's quite easy with some global variables.

I only needed three variables to implement the spinner. I defined them with the vars package, as the routines that will use them are in packages outside the main script...

use vars qw/
@Spinner
$ProgressCount
$BackSpace
/;

@Spinner is a simple array for the characters that make up the spinning wheel, $ProgressCount is an integer that decides which character to display and $BackSpace is, as its name suggests, the delete backwards character.

Then, still in the main script, I only had to initialise them...

@Spinner = ('!', '/', '-', '\\', '!', '/', '-', '\\');
$ProgressCount = 0;
$BackSpace = "\010";

The spinner characters are pretty obvious, except that you need to remember to escape the backslash, to avoid any parsing problems. The progress counter is set to 0 when we begin, although it could be any valid index into the spinner array. The backspace value should work equally well for Windows and Unix systems, although I've only tested it on Windows XP and Apple OS-X so far.

Finally, to use the spinner, you only need three lines, at the point where you're showing the progress...

print $::BackSpace . $::Spinner[$::ProgressCount];
if( $::ProgressCount++ > 6 ) { $::ProgressCount = 0; }
$=1;

The first line backspaces over whatever was there, then shows the currently selected character. The second line increments the progress counter and checks it hasn't got too big. If it has, it resets it. The third line forces Perl to flush the print buffer, thus making sure that we see the progress as it occurs. If you don't do this, you could end up with nothing apparently happening, which rather negates the point of this excercise.

By the way, the syntax '$::varname' just points 'varname' at the calling $main, in this case, our control script.
:

Tuesday, December 16, 2008

It lives, Igor, it lives!

My spare parts, twin screen PC is now running smoothly under 'obsolete' Windows 2000. I've got Vmware Server running guests created in other hosts, provided the guests have been shut down correctly.

I've also come across the dreaded '511 vmware-serverd service is not running' message. This seems to be a general purpose grumble, along the lines of Apache's 404 message.

In my own case, I cleared it by removing all the 'Datastore' lines in

\Documents and Settings\All Users\Application Data\VMware Server\config.ini

Then I went to the Control Panel, ran the Administrative Tools application, selected Computer Management and, from the Services and Applications list, selected the Services item. I restarted the VMware Registration Service and the whole thing sprang to life.

VMware Server is a useful tool but you do need to treat it with care.
:

Sunday, December 14, 2008

Just when you thought it was safe to go back in the water.

I rebuilt my twin screen PC under Windows 2000 and, as expected, it was a simple, straightforward job. Then I loaded VMware Server.

First of all, VMware asked if I wanted to download the new, improved version and I said "yes". As others have discovered before me, this was not a good idea. The first clue was that v2.0.0 is now a whopping 590MByte download, against 1.0.6's sprightly 149MByte. Still, there must be good things to come from all these extra bytes. Perhaps, but not for someone who wants to run on a paltry little AMD XP 2200+ with a miniscule 1GByte of RAM. The good news was that I could keep the Task Manager's performance pane open on one screen, as my outdated box struggled manfully to cope with the demands of the new software. Performance, as the saying goes, sucked. Badly.

So I uninstalled V2 and re-installed V1.0.6.

This should have been the end of the story except, that I discovered something I hadn't known before. All our other PCs are Pentium based, this is the one and only AMD box we have. So all our virtual machines were created on Pentium kit. Well, here's a thing: VMware won't run a guest built under one chipset on a host running a different one.

To be fair, the console will tell you that this is a bad idea but I thought "everything that runs on Pentium runs on AMD XP". No it won't, not if it's a VMware virtual machine. If you ignore the warning and start up the guest, the first time you try to do anything you'll get an error. Living in my closeted Intel bubble I hadn't realised there were major compatibility issues, even though other, wiser heads clearly knew there were.

Apparently, all is not lost. It's alleged that this problem only affects 'Suspended' guests. The theory is that you can migrate a 'Switched Off' guest quite happily. I need to try this and see.
:

Saturday, December 13, 2008

and now for something completely the same

Having failed to get my twin head 'nix system up under Centos and Mandriva, my thoughts turned to things Sun. I have a nice shiny OpenSolaris CD in my disk wallet and it seemed like that might solve my problem.

Two hours later and the answer is 'no'.

Things turned iffy when the installer failed to recognise my network card, a Via Technologies Rhine II that all the other installers had no problem with. It claimed, however, to understand the Nvidia video card and so it did, kind of. It knew enough to recognise the second monitor and even work out its maximum resolution but was not so obliging as to turn it on. This was something of a problem as it decided that the first screen has a maximum resolution of 640 x 480.

I couldn't even activate the second screen, although it was quite clearly visible to the OS, because someone decided that the Nvidia X control panel dialog should have a minimum size of something larger than 640 x 480, which is sort of reasonable given the screens that most people will be working with. The only problem was that I couldn't get to the controls at the bottom of the dialog. Enough of this sort of thing and you start to lose the will to live.

Finally I tried Kubuntu. That didn't even get as far as installing, as it couldn't live with the Nvidia card for some reason.

I like Open Source. In my own small way I've tried to contribute to it. My commercial experience shows that Open Source is displacing Closed Source in the server room, ever more rapidly. The problem is that the server room is the province of geeks, who will spend the time to solve the problems, as I would solve this problem if I was being paid to do so. But I'm not and nor are most people who will be trying to put 'nix on the desktop.

Open Source software can work wonderfully well, when people who know what they're doing take a hand. Look at Apple's OS-X, which is, at heart, FreeBSD. We use several Apple machines and they're amazingly stable and incredibly versatile. Those who don't want to know what's going on under the covers, need never even think about it, while we techie types can go on-site with a laptop that's impressive even in the board room, yet is running one of the best 'nixes in the business.

Linux too can be stable and useful. The Asus Eee portables show what can be done when a commercial organisation take charge, nailing down all the problems and quality engineering the rough edges. I've worked on a couple of projects myself where Linux has been engineered into specialist hardware with great success. The common point here, is that the companies have applied commercial savvy to the process, specified to the last degree what hardware the OS must run on, then tested the bugs out of the combination. That is something that large corporations can do, which loose federations of enthusiasts will always have a problem with.

It's no harsh criticism to say the Open Source movement needs to handle expectations somewhat more carefully than they do. It's just a case of, "look, this is a list of what we know the software can handle. if your stuff isn't on here, you'll need to proceed with caution". Of course, a geek can find that out easily enough, without being told, and quite possibly sort it out, but most of us aren't geeks.

This was intended to be a quick fix and it turned into a saga, so I cut the whole thing short by zapping the partitions and re-installing Windows 2000 across the whole disk (this is the machine that owns the licence, in any case). For the time being, I'll go back to my usual practice of running Linux on the desktop as a guest, under the free Vmware Server system and admit that, until further notice, Windows owns the desktop.
:

Friday, December 12, 2008

Close, but still no cigar

Linux is often proclaimed as the saviour of the benighted computeer. Moved to rightous anger by the beast of Redmond and the clear mastery of Linux, a mighty wave of Unix based systems will sweep away the evil empire of Microsoft and there will be much cheering throughout the galaxy.

Perhaps, but not just yet.

I am, it must be said, a friend of all things 'nix. I've earned a good living from the old bag of bolts for many years and consider myself to have some understanding of what's going on inside a running system. So, when I decided to recycle my wife's old LCD screen, by connecting it to my 'spare' PC, I didn't anticipate much in the way of trouble. Well, as Evelyn Waugh was wont to say, 'Up to a point, Lord Copper'.

I already had a couple of small Windows 2000 partitions on the disk, so I plugged the monitor into the spare socket of my old but perfectly serviceable Nvidia FX5500 and right clicked on the desktop. Select 'Properties', click the 'Settings' tab, pull down the 'Display' list and select 'use both monitors'; whereupon, I have to say, Robert was clearly your mother's brother. Total elapsed time: less than 5 minutes, including playing around with both monitors' settings, to get the best balance.

Ah, I thought, now let's put Linux on the unused disk space and build a twin head 'nix system. As I do a lot of work with Redhat servers, it seemed an obvious step to stick Centos 5.2, the free version of Redhat Enterprise Server, on the disk. This was not a success. As expected, Centos installed happily and soon I was looking at a KDE desktop. On one screen.

Nothing I could do would bring the second screen up as anything other than a psychadelic explosion in a neon tube factory. A few minutes searching turned up several comments, to the effect that the 'community' version of the Nvidia driver can't handle twin screens and you need to download Nvidia's own, proprietory, driver. So I did. It didn't. I could not get that driver to install, it just kept complaining that there was a problem with the installation and falling out.

All right, I thought to myself, we'll have another go. Out came the Madriva 2009 disk and 20 minutes or so later I was looking at, you guessed, one working monitor plus a piece of art guaranteed to get into the finals of the Turner Prize. Sigh.

So I rebooted, only to find that Grub had not got the message about the change in targets, even though Mandriva had claimed to have told it. So I had to boot from my Windows 2000 CD and invoke the recovery console, in order to invoke fixmbr. This is not your everyday DOS command but, when required, there's very little else that will do. So now I have to scrap the Linux partitions and start again.

Well, it's one way to use up a slow Friday.
:

Friday, September 21, 2007

Installing wxWidgets under Apple OS-X

wxWidgets (formerly known as wxWindows) is a very, very useful cross platform GUI development library. In plain English, you can write an application once on any platform, then deploy it easily on a completely different platform. It's Java Swing without the processing overhead!

You'll find that the installation of wxWidgets on an OS-X system is quite straight-forward but the documentation can confuse the newcomer a little. This may help...

Essentially, you first need to have installed the Apple Developer's Toolkit which you can download, free of charge, from the Apple Developer site. Follow the instructions for installing and testing the tools.

With the tool kit installed, and tested, you can then download the wxWidgets distribution for OS-X from the organisation's home page. Unzipping the single download file will create a substantial file tree with a root directory name of the form wxMac-n.n.n, where 'n.n.n' is the version number. I would recomend that you move this tree to the /Developer path created when you installed the Developer's Tool Kit. This just keeps everything together.

The next thing we have to do is make sure that the installation is correctly set up for your system. We do this by running configure, which has been installed with wxWidgets. Before we do this, we need to create a directory into which the wxWidgets libraries will be compiled. It's strongly suggested that you make this directory under your installation directory.

Let's start by running Terminal. Then the first thing we do when the terminal window is open, is to change to the installation directory...

$> cd ../../Developer/wxMac-2.6.1

Now create the directory that we're going to build the library in and then get into it...

$> mkdir osx-build
$> cd osx-build

We're ready to configure the installation for our needs. We call configure from the parent directory and tell it that we want a stand-alone library...

$> ../configure --disable-shared

This just sets up the makefile which will control the installation. You'll see a nice selection of messages as the process proceeds. When it's done, we're ready to create the library with which we'll link our application programmes. All that's required is to invoke make...

$> make

There will be a long wait while the compilation proceeds, there's a lot for it to do. Finally, if all is well, it will come to a natural halt. Now we can test it.

If we do the following...

$> cd samples/minimal
$> make

...we should see the compiler running. Provided it completes normally we do...

$> open minimal.appgt; open minimal.app

A window should open on the desktop and we should see a sample programme with the Aqua look and feel...


Minimal programme screenshot


There's not a lot this basic programme does other than display menus but that should be enough to prove that the installation has worked.

The reason for using open is that wxWidgets on the Mac creates bundled applications. Open is a Darwin executable which emulates, in a Terminal window, the process of double clicking on an application in Aqua.

You can see the effect of the bundling if you look at the samples/minimal directory from the Finder...




You'll notice that there are two 'minimal' applications shown. One is for the Classic environment (up to OS 9) and the other for OS-X. In practice, you'd distribute these in different directories, for the convenience of your users.
:

Thursday, January 4, 2007

Apple OS-X Default Applications

You don't necessarily want to use the Apple applications that come with OS-X, nice as they undoubtedly are.

If you want different applications to open as default when you click on a file, try this: select the file in a Finder window, Ctrl-Click to get the pop-up menu, click on the arrow next to 'Open With:' to show the dialogue, select the application to use from the selection box (you can use the 'other' item right at the bottom to hunt for an application that isn't on the menu). To make your new selection the default application for all files of this type, click the 'Change All' button.

To change the default Internet applications (mail client, browser) in 10.2 or earlier, you need to open System Preferences from the Apple menu, select 'Internet' and follow the dialogue there.

For 10.3 onwards, it's a little trickier. To change the default web browser: start Safari, select 'Preferences' under the 'Safari' menu, select the 'General' tab (the leftmost item) and pull down the 'Default Web Browser' selection box. If the browser you want to use is not offered, choose the 'Select...' item and use the file dialogue to find your browser.

The procedure for choosing a mail client is broadly similar but use Mail instead.
:

Friday, November 17, 2006

Proceeding in an orderly fashion with Oracle



PL/SQL has many endearing features for the programmer and one or two which are less so. One of its nicer features is the ability to define procedures which can then be used as if they were a part of the language. Procedures may define and use variables which are local to that procedure. An extension to this is the concept of packages: bundles of procedures which can be used as complete libraries and slotted in as 'black boxes' wherever they're required. Packages may define variables which are local to the package but global to the procedures contained by the package.

Procedures.

A procedure consists of a name (with optional parameters), IS, BEGIN, any number of statements and END. As with C, Perl and similar languages, each statement is terminated with a ';' (semi-colon). Here's a simple example...

PROCEDURE GetSalesList(Customer IN VARCHAR2, Process in VARCHAR2)
IS
BEGIN
IF Process = 'PURGE'
THEN
DELETE FROM SalesFeed
WHERE CustId in (SELECT distinct Id
FROM Customers
WHERE Name = Customer);
ELSE
INSERT INTO Invoice (CustomerId, TranDate, Value)
SELECT CustId,
FeedDate,
Amount
FROM SalesFeed
WHERE CustId in (SELECT distinct Id
FROM Customers
WHERE Name = Customer);
END IF;
END;

Thre's effectively no limit to how large and complex procedures may be. Once installed in a package, procedures may be called by any query which has access to the package, making this a very useful facility.
:

Saturday, July 29, 2006

SQL*Plus: Oracle's Swiss Army Knife

For a very long time, Oracle has shipped with the SQL*Plus application as standard.

There are different versions for different operating systems but users will, most commonly, come across the versions for Microsoft Windows and those for the Unix family. The difference between these is that the Windows version is a fairly basic application whereas that for Unix is a very powerful tool indeed because it allows you to use it as a standard command line application like any other, so permitting its use in complicated shell scripts.

What a lot of people don't realise is: there's a CLI version of SQL*Plus installed along with the not terribly useful Windows version which, within the limitations of Windows, permits all the flexibility of the Unix variant.





Once you know this, your ability to automate Oracle tasks on Windows is increased dramatically. While not quite as flexible as the Unix version, due to the limitations of Windows, there are still many things you can do that are just too much of a pain when using the GUI version.

Wednesday, March 15, 2006

Some Awk Tips and Tricks

Finding the length of a line.

A colleague needed to find the length of a particular line in a file. He discovered that using 'wc' gave the wrong result (as in "head -2 filename | tail -1 | wc -c"). Here's what he came up with instead. Note the parentheses...

cat filename | awk '{ if ( NR == 2 ) {print length($0); exit; } } '

Sizing a directory.

This uses Awk's ability to do arithmetic across multiple input lines to produce a count, total and average file size for a directory or a supplied pattern. It's a usefull tool for quick 'n' dirty system admin...

echo "file counter and sizer"
echo "----------------------"
if [[ -z $1 ]]
then
echo "Sizing entire directory"
else
echo "Sizing files for pattern [$1]"
fi

ls -l >/tmp/fsz.$$_1

# -------------------------------
# Remove any directory entries...
# -------------------------------
grep -v ^total /tmp/fsz.$$_1 | grep -v ^d >/tmp/fsz.$$
rm /tmp/fsz.$$_1
# ------------------------
# Set up the search job...
# ------------------------
if [[ -z $1 ]]
then
cat /tmp/fsz.$$
| awk '{s += $5}; END
{printf "\nThere are %d files matching pattern\nAverage size is %f\nTotal size is %f\n", NR, s/NR, s}'

else
grep $1 /tmp/fsz.$$ | awk '{s += $5}; END {printf "\nThere are %d files matching pattern\nAverage size is %f\nTotal size is %f\n", NR, s/NR, s}'
fi
rm /tmp/fsz.$$


Don't use awk - use nawk!

I couldn't work out why this wouldn't work when I ran it using awk (as it worked fine on another machine). It turned out that it would perform admirably if I ran it using nawk instead. It's worth trying this out on your own machine and seeing what happens...

nawk '{ if(substr($0,405,2)=="LS") print $0 }' sourcefile.dat | head -10000 > targetfile.dat
:

Thursday, July 21, 2005

The when and the wherefor

Dates in Perl are a pretty big subject but the essence can be reduced to two simple rules: use 'localtime' to retrieve Perl's internal date block and then use 'sprintf' to format the retrieved date. The following subroutine returns the current date and time in the format 'dd-MMM-yy hh:mm' (e.g. 23-DEC-05 15:35)...

sub FormatCurrentDateAndTime
{
my $V_CURRENT = localtime;
my $V_SECOND = substr($V_CURRENT, 17, 2);
my $V_MINUTE = substr($V_CURRENT, 14, 2);
my $V_HOUR = substr($V_CURRENT, 11, 2);
my $V_DAY = substr($V_CURRENT, 8, 2);
my $V_MONTH = uc(substr($V_CURRENT, 4, 3));
my $V_YEAR = substr($V_CURRENT, 20, 4);

# -------------------------------
# And Format the output string...
# -------------------------------
$V_ID_STRING = sprintf("%02d-%s-%02d_%02d:%02d",
$V_DAY,
$V_MONTH,
$V_YEAR,
$V_HOUR,
$V_MINUTE);
TraceScript $Debug,
"MakeDateTimeID",
"Generated id is [" . $V_ID_STRING . "]";

return $V_ID_STRING;
}

The above code is very simple. Calling localtime without an argument gets the current date and time which is then sliced up into the named variables. Sprintf is then called to reformat the value the way we want it. The TraceScript call gives the clue that this particular example is being used to generate a unique ID.
:

Monday, July 11, 2005

Getting at the bits

One place that Perl scores very highly is reading complex file formats. A really useful built-in function for this purpose is split(). This takes a divider and a string, whose length is only limited by Perl's string handling limit. The divider is in the form of a regular expression, so it can be as complicated as you wish. Split() returns an array, with each piece of the original string as an element, broken up according to the regex and the divider(s) removed. Say, for example, you wrote ...

@Result = split(/:/, "apples:oranges:pears"

then @Result would contain the elements

apples
oranges
pears

with the dividing ':' discarded. The following, real life, example is for extracting the required item from a comma-delimited list, such as a line in a CSV file...

sub GetCsvElement
{
my @V_ARRAY;
my $P_ELEMENT = $_[0];
my $P_SOURCE_STRING = $_[1];
my $V_RESULT;

# -----------------------------------
# Drop the elements into our array...
# -----------------------------------
@V_ARRAY = split (/,/, $P_SOURCE_STRING);

# ----------------------------------------------------------------
# Arrays are zero based so we pick one less than the passed value!
# ----------------------------------------------------------------
$V_RESULT = trim $V_ARRAY[--$P_ELEMENT];

# ----------------------------
# Return the requested item...
# ----------------------------
return $V_RESULT;
}

Remember, because you're using a regular expression to define the delimiter, you can process multiple types of line or even lines with more than one delimiter.
:

Saturday, July 2, 2005

Perl sans frontiers

I often want to retrieve results from an external process within a Perl script. In theory, this is easy. All you need to do is something like...

$Result = `ls *.sql`

...which works perfectly well on any Unix (or Linux) system. The problem is that it doesn't work at all on Windows so, if you want your programme to be fully portable, you need a workaround. My solution is to use the one common feature on both Windows and Unix, the redirection character (>).

Say I want to run a SQL query (because this is something I do frequently, I have a subroutine for it)...

# =======================================
# Runs an SQL file, returning the result.
# ---------------------------------------
# $_[0] is the connection string.
# $_[1] is the file to run.
# $_[2] is a file to write the result to.
# ---------------------------------------
# (This last is necessary because the ``
# syntax does not work in Windows.)
# =======================================
sub RunSqlQuery
{
my $V_COMMAND = "sqlplus "
. $C_SQLPLUS_FLAGS
. " "
. $_[0]
." \@"
. $_[1]
. " >"
. $_[2];
my $V_RESULT;

# --------------------------------
# Run the command created above...
# --------------------------------
system $V_COMMAND;

# ---------------------------------
# Get the result back from the file
# and send it up the call chain...
# ---------------------------------
$V_RESULT = ReadResultFile $_[2];
return $V_RESULT;
}

Now the above piece of code will work, unaltered, on both Windows and Unix. Then all we need to get at the result is a matching sub-routine to read the file...

# ===============================================
# Reads a file in which a result has been placed.
# -----------------------------------------------
# $_[0] name of the file to read.
# -----------------------------------------------
# This is one of the workarounds made necessary
# because the syntax "VAR=`command`" does not
# work in Windows the same as it does in Unix.
# ===============================================
sub ReadResultFile
{
my $V_BUFFER;
open(H_SQL_FILE, "<$_[0]") or die "FAILURE: Cannot open " . $_[0];
read H_SQL_FILE, $V_BUFFER, 65535;
close H_SQL_FILE;
return $V_BUFFER;
}

The size limit of 65535 bytes is completely arbitrary and can be altered to meet the specific requirements of the application.
:

Thursday, June 30, 2005

What's your name?

I really like how easy Perl makes things. Take filename handling. I don't know about you but I spend a lot of time breaking filenames apart and reforming them. Perl turns it into a doddle and a quick sub-routine makes it even easier...

# ==================================================
# Gets a specified component from a given file name.
# --------------------------------------------------
# $_[0] Component to extract: 'PATH', 'FILE' or 'EXT'
# $_[1] Full file name to extract from
# --------------------------------------------------
# Returns the base filename
# Examples...
# GetPathComponent "FILE", "\anypath\Test1.scr"
# returns "Test1"
# GetPathComponent "PATH", "\anypath\Test1.scr"
# returns "\anypath\"
# GetPathComponent "EXT", "\anypath\Test1.scr"
# returns ".scr"
# --------------------------------------------------
# $C_LOCAL_OS must be set to use with DOS filenames.
# $C_EXTENSION_PATTERN must be set to a valid
# pattern for the extension before calling this
# routine. A typical value is \\..*? which will
# work for both DOS and Unix.
# ==================================================
sub GetPathComponent
{
my $P_COMPONENT = $_[0];
my $P_FULL_NAME = $_[1];
my $P_OS_NAME = $_[2];
my $V_BASE_NAME;
my $V_PATH_NAME;
my $V_FILE_EXT;

# -----------------------------------------------------
# DOS uses the escape character (\) as a path seperator
# which defeats the fileparse function, so convert any
# escape character to a forward slash first...
# -----------------------------------------------------
if( $C_LOCAL_OS eq "DOS" ) { $TESTVAL =~ s/\\/\//g; }

# -----------------------------------------
# The fileparse sub does the actual work...
# -----------------------------------------
($V_BASE_NAME, $V_PATH_NAME, $V_FILE_EXT)
= fileparse($P_FULL_NAME, $C_EXTENSION_PATTERN);

# -----------------------------------------------------
# Return the requested component (or die if invalid)...
# -----------------------------------------------------
if($P_COMPONENT eq "PATH") { return($V_PATH_NAME); }
elsif($P_COMPONENT eq "FILE") { return($V_BASE_NAME); }
elsif($P_COMPONENT eq "EXT") { return($V_FILE_EXT); }
else {die "Invalid component ["
. $P_COMPONENT
. "] specified in GetPathComponent" }
}

Simple, isn't it? I could have treated the return value from fileparse() as an array but I prefer to use descriptive filenames wherever possible. I'm funny that way.
:

Saturday, May 7, 2005

You say potato and I say tomato

I've been thinking about the names people give to variables and functions. It's scary to see just how many instances of $i and 'fred' there are in supposedly professional code. As it's spring, how about cleaning up your code so that others can maintain it without wrapping a wet towel round their aching heads?

The first rule of naming is that names should add to the reader's understanding rather than obscuring it. For example, The name of a function that returns an element of an array should be something like GetNextCustomer() rather than GetNextArrayElement().


Some other general points about naming...
  • If you have difficulty in finding an appropriate name for a function, procedure or object then you may need to further analyse or define the purpose of that item.
  • Names should be long enough to be meaningful but no longer.
  • Remember that names have no meaning to the compiler/interpreter other than to distinguish one item from another.

Some rules that you may wish to follow include...
  • Use mixed case to aid readability. Capitalise the first letter of each word in a function or procedure name and the same for variable names but with the very first character in lower case. Thus a procedure might be called SortNewCustomers while a variable migh be called customerName.
  • Use all capitals with words seperated by underlines for constants as in TOTAL_SHOPS or SALES_BAND_A.
  • Don't use names that are ambiguous, such as AnalyzeThis() for a routine, or A47 for a variable.
  • Don't include class names in the names you give to class properties, such as Customer.CustomerID. Instead, use Customer.ID.
  • If a routine performs an operation on a given object, include the object name in the routine's name, as in ValidateCustomerID().
  • Never overload a function in such a way that it performs * In languages that permit function overloading, all overloads should perform a similar function. For those languages that do not permit function overloading, establish a naming standard that relates similar functions.
  • Where a variable holds the result of a computation, add the type of computation to the end of the variable name as in salesAvg, customerSum, temperatureMin, temperatureMax, customerIndex) and so on.
  • When producing complementary pairs of variables, name them appropriately, e.g. min/max, begin/end or open/close.
  • If a variable is Boolean i.e. it contains only Yes/No or True/False values, use a name which highlights this such as fileIsFound or customerIsValid.
  • Avoid the lazy use of terms like Flag when naming status variables. Instead of documentFlag, use a more descriptive name such as documentFormatType.
  • Always avoid single character variable names in loops and so on. "for ThisShop = 1 to TOTAL_SHOPS" is far more informative than "for i = 1 to 23"
  • Never use literals for constants. Always assign values to constants in a single place at the top of the programme for the good and sufficient reason that constants need changing surprisingly often!

Some points that apply particularly to database handling...
  • When naming tables, express the name in the singular form. For example, use Employee instead of Employees.
  • When naming columns of tables do not repeat the table name; for example, avoid a field called EmployeeLastName in a table called Employee.
  • Do not incorporate the data type in the name of a column. This will reduce the amount of work should it become necessary to change the data type later.
  • Do not prefix stored procedures with sp, which is generally a prefix reserved for identifying system stored procedures.
  • Do not prefix user-defined functions with fn_, which is generally a prefix reserved for identifying built-in functions.
  • Do not prefix extended stored procedures with xp_, which is generally a prefix reserved for identifying system extended stored procedures.

Other points you may wish to consider...

  • Don't abbreviate unless you must. If you do, use those that you have created consistently. Any abbreviation should have only one meaning and likewise, each abbreviated word should have only one abbreviation. For example, if you use min to abbreviate minimum, do so everywhere and do not use min to also abbreviate minute.
  • When naming functions, include a description of the value being returned, such as GetCustomerName().
  • File and path names should also accurately describe their purpose such as SalesTransferFile or SalesFileDirectory.
  • Don't use easily confused names for multiple items. Especially avoid confusions such as a routine called ProcessSales() and a variable loaded from it called iProcessSales.
  • Try to avoid words that sound the same (homonyms), such as 'write' and 'right'. They can lead to all sorts of confusion when several people work on a project.
  • Use the appropriate spelling for your contry such as color/colour or check/cheque.
  • It's no longer considered valid to use character type identifiers, such as $ for strings or % for integers as various languages, such as Perl, reserve these symbols.

Followers

Who is this Sejanus character anyway?

I'm a British freelance Analyst Programmer who has spent the last 25 years working on everything from microcontrollers to mainframes. I use a wide variety of languages at work but try to stick to C and Perl for my own projects.