eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:
Our code runs on three broadly different platforms: Unix (many variants), NSK, and Windows. Typically, the Unices are similar enough that we use the same code on all variants, but the NSK and Windows code is often completely different.
I noticed some existing code structured like this:
use strict; sub win_fn { print "windows version of function\n" } sub nsk_fn { print "nsk version of function\n" } sub unix_fn { print "unix version of function\n" } sub xplatform_fn { if ($^O eq 'MSWin32') { return win_fn(); } elsif ($^O eq 'nonstop_kernel') { return nsk_fn(); } else { return unix_fn(); } } xplatform_fn();
I'm seeking a better way to structure this type of code. I've taken a look at how File::Spec does it and whipped up two different approaches as shown below.
use strict; my $OS_TYPE = $^O eq 'MSWin32' ? 'win' : ($^O eq 'nonstop_kernel' ? 'nsk' : 'unix'); sub win_fn { print "windows version of function\n" } sub nsk_fn { print "nsk version of function\n" } sub unix_fn { print "unix version of function\n" } my %xplat = ( 'win' => \&win_fn, 'nsk' => \&nsk_fn, 'unix' => \&unix_fn, ); sub xplatform_fn { return $xplat{$OS_TYPE}->() } xplatform_fn();
and:
use strict; my $OS_TYPE = $^O eq 'MSWin32' ? 'win' : ($^O eq 'nonstop_kernel' ? 'nsk' : 'unix'); sub XPlat::win_fn { print "windows version of function\n" } sub XPlat::nsk_fn { print "nsk version of function\n" } sub XPlat::unix_fn { print "unix version of function\n" } sub xplatform_fn { return &{$XPlat::{$OS_TYPE."_fn"}} } xplatform_fn();
What I'm after is examples of nice, clean, general ways to structure cross-platform code.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Seeking good ways to structure cross-platform code
by Corion (Patriarch) on Sep 29, 2004 at 06:40 UTC | |
by Roger (Parson) on Sep 29, 2004 at 07:17 UTC | |
by eyepopslikeamosquito (Archbishop) on Sep 30, 2004 at 02:15 UTC | |
|
Re: Seeking good ways to structure cross-platform code
by simonm (Vicar) on Sep 29, 2004 at 06:37 UTC | |
|
Re: Seeking good ways to structure cross-platform code
by dragonchild (Archbishop) on Sep 29, 2004 at 12:35 UTC |