|laziness, impatience, and hubris|
Cross platform compatability Part 1: Shells and Filesby jepri (Parson)
|on Jan 21, 2001 at 12:39 UTC||Need Help??|
This is a fairly difficult topic to broach, because a lot of people here are on Unix style systems and are likely to blow off the whinging windows user. This is unfortunate, because there are a lot more OSs out there than windows and Unix. You want your code to run cleanly on all of them, right? After all you're programming Perl, not Perl/Linux, right? I'm appealing to your pride here.
There isn't much you have to be aware of, but you may feel a little discomforted by having to give up some amazingly cool shell tricks. I think there are replacements for almost all of them.
Don't make the shell do work that Perl canThe favourite for most Unix coders is to use shell tricks to loop over the files in a directory, like this
and insist the the user run:
perl parsedir.pl /home/me/*
The shell (bash, sh, ksh, etc.) expands the * into the list of filenames and hands it to the your program. Unfortunatly DOS/Windows doesn't. You can't rely on the shell working correctly under *nix anyway. A system manager may decide to restrict scripts to running on some primitive shell for memory or security reasons. Use
See here for a nice example.
Don't include specific filesystem symbolsA quick way to do temporary files is:
except that it breaks DOS machines.
DOS/Windows coders can get their revenge by using
You shouldn't be using hard-coded parameters in your program anyway. It will bite you later when you realise you need the temporary file in a different place, and have to go trolling through your code to find all the places you hard-coded it. This is easily solved by placing:
Always finish your directory names with the directory symbol (forwards or backwards slash or whatever).
Don't use external utilitiesPerl has a perfectly good regexp engine. It's probably a lot better than grep. If you're running perl, don't shell out to grep:
`ls -lR | grep myfile`;
is an abomination.
The ls -lR is a problem, because it does a directory recursion much more easily than File::Find. If you're doing a serious script though, you should be File::Find. There's even a wrapper for it now, so it's easier to use.
I hope these few examples have given you a bit of direction when it comes to making your scripts cross-platform. I'm not saying your three-line file parser should be platform independent, but if you're submitting a one-page program to the monastery it would be nice if the windows users could cut'n'paste it too.