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.
:

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.