http://qs321.pair.com?node_id=156419

RhetTbull has asked for the wisdom of the Perl Monks concerning the following question:

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