[thelist] Parsing filenames in Perl

Mike Combs mike at combsnet.com
Wed May 8 19:11:01 CDT 2002


This is probably soooo obvious that there was no reason for there to be a
web page that clearly explained this.  But just in case...

Also, if I've done something wrong, I'm inviting pointers from the real
experts.

<tip type="Parsing uploaded filenames in Perl" author="mike at combsnet.com">

I have a Perl script that accepts uploaded files.  The problem is that the
filename has different delimiters, depending on the OS the user uploaded it
from.  This Perl script seems to do the trick:

# somewhere at the head of your script
Use File::Basename;

# in the chunk of code just after you've gotten the filename into $fname
	$os_string = "VMS"; # /mydir/myfile.txt
	if ($FORM{$name} =~ /\:/) { $os_string = "MacOS"; } # mydrive:mydir:myfile.txt
	if ($FORM{$name} =~ /\\/) { $os_string = "MSDOS"; } # c:\mydir\myfile.txt
	fileparse_set_fstype($os_string);
	($name,$path,$suffix) = fileparse($fname,'\..*');

The trick here are the three lines that figure out what OS the uploaded
file came from.  Otherwise, fileparse defaults to the OS that it's running
on.  This isn't a problem if it's running on Windows and visitors to your
site are running Windows, but if you're not that lucky, this tip may be handy.
</tip>





More information about the thelist mailing list