Platform-Specific Perl

in Perl Tips, Files & Directories
by William Ward on October 2, 2006 8:29 pm

As an interpreted language, Perl scripts can generally be run unmodified on any platform. But there are situations where the differences between platforms make it necessary to test what platform you are running on and act accordingly.

Say, for example, that you need to change permissions on a file. On Unix and related operating systems (including Mac OS X and Linux) you would use the chmod function, but that doesn’t do much on Windows. Although the chmod command will execute on Windows it doesn’t do much. Traditional FAT filesystems have only four attributes per file: archived (A), read-only (R), hidden (H), and system (S). These can be checked and set with the Win32::File module. For NTFS, use Win32::FileSecurity.
(For more information about Perl on Windows, see the Perl Win32 FAQ.)

So, in your program, if you want to be able to do one thing on Windows and another on Unix-like systems, you need to test what platform you are on. The way to do that in Perl is to look at the special variable $^O. (That’s the letter O, not the number 0). If you’re on Windows, it will have the value “MSWin32″ (sadly, it doesn’t give you any clue what version of Windows you’re on). So you would do something like this:

if ($^O eq "MSWin32") {
    require Win32::FileSecurity;
    Win32::FileSecurity::Set($file, { ... })
        or die "Error in FileSecurity for $file: $^E";
}
else {
    chmod 0644, $file
        or die "Error in chmod for $file: $!";
}

To find out what the value of $^O is on your platform, run this little command from your shell:

perl -e "print $^O";

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment