in reply to Seeking good ways to structure cross-platform code

I approach this a bit differently, by having n+1 modules for n platforms like this:

package My::Functions; use strict; my $OS_TYPE = $^O eq 'MSWin32' ? 'win' : ($^O eq 'nonstop_kernel' ? 'nsk' : 'unix'); if ($OS_TYPE eq 'win') { require My::Functions::Win32; } else { require My::Functions::Unix; }; 1; # ---- File My/Functions/Win32.pm: package My::Functions::Win32; package My::Functions; sub foo {}; # ---- File My/Functions/Unix.pm: package My::Functions::Unix; package My::Functions; sub foo {};

That way, I lose access to the Unix functions under Win32 and vice versa, but the functions live all in the My::Functions namespace and not below it, which I find nice and more convenient. Functions common to all platforms end up in My/Functions.pm.

Replies are listed 'Best First'.
Re^2: Seeking good ways to structure cross-platform code
by Roger (Parson) on Sep 29, 2004 at 07:17 UTC
    I like Corion's approach, in fact I use a similar approach as well. I think this approach is cleaner than mixing codes for different platforms into a single module.

    My similar approach:

    package My::Functions; ... my $OS_TYPE = ...; eval "require My::Functions::$OS_TYPE" or die "Can not load module"; ..


    Having said that, simon's approach from File::Spec is nice too. As Perl programmers always quote: there is more than one way to do it. :-)

Re^2: Seeking good ways to structure cross-platform code
by eyepopslikeamosquito (Archbishop) on Sep 30, 2004 at 02:15 UTC

    Thanks Corion. I'm now using your approach and am very happy with it. I've changed $OS_TYPE to be 'Win32' and 'Unix' so I could replace:

    if ($OS_TYPE eq 'win') { require My::Functions::Win32; } else { require My::Functions::Unix; };

    with:

    eval "require My::Functions::$OS_TYPE";

    or:

    require "My/Functions/$OS_TYPE.pm";

    Both seem to work ok. Is there a reason to prefer one over the other?