문제

Which way should I use?

package My_Module;

# way one
my $package = $^O eq 'MSWin32' ? 'My_Module::Win32' : 'My_Module::Linux';
sub new {
    my $class = shift;
    return $package->new( @_ );
}

# way two
use parent $^O eq 'MSWin32' ? 'My_Module::Win32' : 'My_Module::Linux';
도움이 되었습니까?

해결책

Personally I'd go with the first technique. Creating a class that sometimes inherits from one parent, and sometimes inherits from another, seems a little dirty to me. It'll work certainly, but it will confuse class analysis tools (like Pod::Coverage::CountParents) no end.

That said, I'd probably rename sub new to something like new_by_platform. There's a strong expectation that My_Module->new will return an object of type My_Module. Having it return an object of another class could confuse people. (Though if My_Module::Win32 and My_Module::Linux inherit from My_Module, then naming it new seems less bad.)

다른 팁

2 - use parent is the better way to go about it.

http://lo-f.at/glahn/2009/08/useBaseAnduseParent.html

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top