Thread Methode von anderem Modul benutzen (10 answers)
Opened by gast_kuerbis at 2019-07-04 10:22

rosti
 2019-07-05 10:26
#190167 #190167
User since
2011-03-19
3193 Artikel
BenutzerIn
[Homepage]
user image
Idee: validate_options() als eigenständige Methode (Trait) auslagen. Dateiname: validate_options.pm Inhalt:

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Filename validate_options.pm
use strict;
use warnings;
use Carp;

sub validate_options{
    my $self = shift;
    my $valid = shift; # hasref valide key's
    my $opt   = shift; # hashref Options

    return if ! defined $opt;
    my $sub =  ( caller( 1 ) )[3];
    $sub =~ s/^.+::(?:__)?([^:]+)\z/$1/;
    $sub .= ':';
    for my $key ( keys %$opt ) {
        if ( ! exists $valid->{$key} ) {
            croak "$sub '$key' is not a valid option name";
        }
        next if ! defined $opt->{$key};
        if ( $valid->{$key} eq 'Str' ) {
            croak "$sub $key => references are not valid values." if ref $opt->{$key} ne '';
        }
        elsif ( $opt->{$key} !~ m/^$valid->{$key}\z/x ) {
            croak "$sub $key => '$opt->{$key}' is not a valid value.";
        }
        $self->{$key} = $opt->{$key};
    }
}

1;



Und so wirds genutzt:

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use strict;
use warnings;
use validate_options; # Factory Method

sub new{
    my $class = shift;
    my %opts  = @_;
    my $self = bless{}, $class;
    $self->validate_options({name => 'foo'}, \%opts);
}


my $o = main->new( foo => 'bar' );
# new: 'foo' is not a valid option name at ...


my $o = main->new( name => 'foo' ); # OK!



MFG
Last edited: 2019-07-05 10:33:15 +0200 (CEST)

View full thread Methode von anderem Modul benutzen