My problem

I have a subroutine that is used by my program but whose implementation depends on information not known until runtime (e.g. which OS is the program running under). The subroutine depends on some modules which depend on the OS. E.g. if I'm running under Windows, I use Win32::some_module and my sub uses that module but if I'm on linux I use some::other::module and the sub would use routines from that. I wrap this all in a sub to hide the gory details from the main script.

My solution

I use eval/require/import to get the right modules and define the sub accordingly at runtime. For example
#!/usr/bin/perl use strict; use warnings; if ($^O eq 'MSWin32') { eval q( require module1; import module1; sub bar { print "Win32\n"; } ); } else { eval q( require module2; import module2; sub bar {print "not Win32\n"; } ); } #later in the program... #we don't care what OS is running -- implementation details are hidden bar();

My question

This works fine. What I want to know, does anyone have any better ideas for implementing this sort of thing? Is there a more elegant solution? Are there any potential pitfalls with the solution I'm using? Of course, all of this could be wrapped in a package to make it more transparent to the calling script but I'm interested to know how others have handled this sort of thing.

--RT

In reply to Runtime module use and sub definitions by RhetTbull

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.