in reply to Writing portable code
Module::Implementation provides an easy way to load the "best" of multiple implementations of the same function. Its documentation mostly revolves around the situation where you have an XS implementation and a pure Perl implementation, and wish to load the XS if posssible, but fall back to pure Perl. But it works just as well to switch between OS-specific implementations, or Perl-version-specific implementations.
That said, Perl does have conditional compilation. It's just not very pretty...
BEGIN { $^O eq 'Win32' ? eval q[ sub f { ... } ] # Win32 implementation : eval q[ sub f { ... } ] # Linux implementation };
Update: For longer pieces of code, heredocs look quite nice...
BEGIN { eval($^O eq 'Win32' ? <<'WIN32' : <<'LINUX') }; sub f { print "f-w\n" } sub g { print "g-w\n" } WIN32 sub f { print "f-l\n" } sub g { print "g-l\n" } LINUX
Update II: Also, bear in mind that constants used in conditionals are optimized away by the compiler, so:
use constant BROKEN_FORK_IMPLEMENTATION => ($^O eq 'Win32'); sub f { if (BROKEN_FORK_IMPLEMENTATION) { ...; } else { ...; } }
... the conditional should be optimized away at compile time, so you don't get the overhead of a string comparison operation every time the function gets called.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Writing portable code
by rovf (Priest) on Mar 08, 2013 at 13:40 UTC |