如何從 Moose 包中匯出正常的非 OO 子例程?在常規包中,我會使用Exporter,@ISA和@EXPORT.
uj5u.com熱心網友回復:
Moose 用于構建類和角色。雖然您在技術上也可以匯出函式,但這不一定是最好的主意。
這是一個示例 Moose 類,它也匯出一個函式。
MyApp/Widget.pm
use v5.26;
use warnings;
package MyApp::Widget;
use Exporter qw( import );
our @EXPORT_OK = qw( is_widget );
use Moose;
use namespace::autoclean -except => 'import';
has name => ( is => 'ro', isa => 'Str', required => 1 );
sub is_widget {
my $object = shift;
blessed( $object ) and $object->isa( __PACKAGE__ );
}
__PACKAGE__->meta->make_immutable;
以下是您可以如何使用它:
use v5.26;
use warnings;
use MyApp::Widget qw( is_widget );
my $w = 'MyApp::Widget'->new( name => 'Foo' );
say is_widget( $w );
say $w->is_widget;
請注意,盡管is_widget它是一個可匯出的函式,但它也可以作為方法呼叫!在這種情況下,這是一個特性而不是一個錯誤,但這通常會帶來不便。
一個更好的主意可能是創建兩個單獨的包:一個用于您的類,一個用于您的可匯出函式。
MyApp/Widget.pm
use v5.26;
use warnings;
package MyApp::Widget;
use Moose;
use namespace::autoclean;
has name => ( is => 'ro', isa => 'Str', required => 1 );
__PACKAGE__->meta->make_immutable;
我的應用程式/Util.pm
use v5.26;
use warnings;
package MyApp::Util;
use Exporter qw( import );
our @EXPORT_OK = qw( is_widget );
use Scalar::Util qw( blessed );
sub is_widget {
my $object = shift;
blessed( $object ) and $object->isa( 'MyApp::Widget' );
}
1;
你會像這樣呼叫使用你的包:
use v5.26;
use warnings;
use MyApp::Widget;
use MyApp::Util qw( is_widget );
my $w = 'MyApp::Widget'->new( name => 'Foo' );
say is_widget( $w );
因為 Moose 類和 Exporter 現在完全分開了,所以您不能再呼叫$w->is_widget- 它完全是一個函式,不再是一個方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450438.html
