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.


In reply to Seeking good ways to structure cross-platform code by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.