Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-16 07:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found