Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Writing portable code

by tobyink (Abbot)
on Mar 08, 2013 at 09:51 UTC ( #1022369=note: print w/replies, xml ) Need Help??

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.

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^2: Writing portable code
by rovf (Priest) on Mar 08, 2013 at 13:40 UTC
    For longer pieces of code, heredocs look quite nice...
    This is great!!!! I did not consider combining several HERE documents, but after re-reading the section in perlop, I understand that for my particular application, this might indeed one way to go!

    Ronald Fischer <>

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1022369]
[usemodperl]: this is crazy, the web is broken!
[usemodperl]: just because of banking apps on free wifi, and porn, i guess...
usemodperl thinks every1 should serve HTTP on port 80 incase we don't care about encryption, right? wtf

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2018-06-24 09:31 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.