Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

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 RUNNING_IN_HELL => ($^O eq 'Win32'); sub f { if (RUNNING_IN_HELL) { ...; } 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


Comment on Re: Writing portable code
Select or Download Code
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 <ynnor@mm.st>

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1022369]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (13)
As of 2014-09-18 19:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (122 votes), past polls