Thursday, October 2, 2008

Perl Snippet

Recently, I have been moving Perl scripts from BSD and Linux machines onto OS X. Mostly, things are pretty smooth but today I had to change a script slightly so that I could read data from /private/var/tmp/ on OS X. The scripts I had on the other systems would read from /var/tmp/, on OS X there is a symlink to /private/var in the root partition, but it seemed to me that relying on the existence of symlinks is not a particularly good idea. Especially if I would need to move the scripts onto another system in the future.

I searched around my trusty Perl documentation and of course, online at http://perldoc.perl.org/ and I found I could use a special variable that contains the operating system name. Here's what I came up with:


my $infile = $ARGV[0];
my $os = $^O; # woohoo there's a special variable I can use for this

get_xmlpath();

sub get_xmlpath
{
if ( $os eq "darwin" )
{
$xmlpath = '/private/var/tmp/xml-data/';
}
else
{
$xmlpath = '/var/tmp/xml-data/';
}
$infile = "$xmlpath$infile.xml";
print "Using XML file: " . $infile . "\n";
return ($infile);
}

Could it be done using less lines? Of course, but then I think Perl Golf is just plain dumb. Disclaimer: this will not work on Win32, fortunately I never have to use Perl on Win32.

No comments:

Post a Comment