in reply to Re^2: Modules and crossplatform code
in thread Modules and crossplatform code

Perhaps a trick stolen from File::Spec could help you? Have a class defining an OS-independant interface, make that class inherit from OS-specific classes. Make the OS-specific classes inherit from an OS-independant base class, if needed.

Something like this:

Update: Use one file per package (<code> block), don't stuff everything into a single file.

package Foo::Bar; use strict; use warnings; use parent "Foo::Bar::$^O"; # will die here for any OS not yet support +ed 1; =pod Documentation here =cut
package Foo::Bar::MSWin32; use strict; use warnings; use parent 'Foo::Bar::base'; use Win32::OLE; sub frob { Win32::OLE->... } # ... 1;
package Foo::Bar::unixoid; use strict; use warnings; use parent 'Foo::Bar::base'; sub frob { # do it without Win32::OLE } # ... 1;
package Foo::Bar::linux; use parent 'Foo::Bar::unixoid'; 1;
package Foo::Bar::solaris; use parent 'Foo::Bar::unixoid'; 1;
package Foo::Bar::cygwin; use parent 'Foo::Bar::MSWin32'; # assuming you can use OLE with cygwin + - never tried it 1;
package Foo::Bar::base; use strict; use warnings; sub new { my $proto=shift; my $class=ref($proto)||$proto; my $self=bless {},$class; $self->init(@_) or die "init() failed"; return $self; } sub init { # ... } sub some_generic_function { # ... } 1;

And elsewhere in your code:

use Foo::Bar; my $f=Foo::Bar->new(); $f->frob('bla','bla'); $f->some_generic_function();

If you don't like or don't need OOP, add something similar to File::Spec::Functions.

Note that you don't need to inherit from Exporter with any sufficiently modern Perl, even if File::Spec::Functions does. File::Spec is old code, with its own set of problems. It's good, but not perfect. Using File::Spec::Unix as default is ok, but making all other classes inherit from File::Spec::Unix looks strange. And File::Spec also has a design problem.

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Replies are listed 'Best First'.
Re^4: Modules and crossplatform code
by Corion (Patriarch) on Dec 07, 2010 at 11:25 UTC

    Keeping Foo::Bar::Win32 in the same file as Foo::Bar::unixoid and having use statements in Foo::Bar::Win32 will not work the way you would like. Loading the appropriate module from a separate file at runtime will only (try to) load a module on Win32 when run on Win32.

    If you really want to keep all things in one file, you will need to change the use statements to require statements together with a call to ->import.

      I never said to put all classes into a single file. I used one code block per file (but forgot to write that).

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)