Thread Automatisches Warning bei falschem Kontext für Funktion (15 answers)
Opened by LanX- at 2009-06-03 16:49

renee
 2009-06-05 08:43
#122359 #122359
User since
2003-08-04
14371 Artikel
ModeratorIn
[Homepage] [default_avatar]
Man könnte es mit Attributen machen:

CheckContext.pm:
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package CheckContext;

use strict;
use warnings;

use Attribute::Handlers;

sub VOID : ATTR(CODE) {
    my ($pkg,$sym,$code) = @_;
    
    my $name = *{$sym}{NAME};
    no warnings 'redefine';
    
    *{ $sym } = sub {
        my $context = wantarray;
        if( defined $context ) {
            die "sub have to be called in void context";
        }

        $code->( @_ );
    }
}

sub SCALAR : ATTR(CODE) {
    my ($pkg,$sym,$code) = @_;
    
    my $name = *{$sym}{NAME};
    no warnings 'redefine';
    
    *{ $sym } = sub {
        my $context = wantarray;
        unless( defined $context and not $context ) {
            die "sub have to be called in scalar context";
        }

        $code->( @_ );
    }
}

sub LIST : ATTR(CODE) {
    my ($pkg,$sym,$code) = @_;
    
    my $name = *{$sym}{NAME};
    no warnings 'redefine';
    
    *{ $sym } = sub {
        my $context = wantarray;
        unless( defined $context and $context ) {
            die "sub have to be called in list context";
        }

        $code->( @_ );
    }
}

1;


Dieses Modul stellt die Attribute zur Verfügung. Mehr zu Attributen, habe ich auch mal in $foo (Ausgabe 5) geschrieben.

Dann ein Modul, das bei den Funktionen die Attribute einsetzt:
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package CheckTest;

use strict;
use warnings;
use base 'CheckContext';

sub test : VOID {
    print 'hallo';
}

sub zwo : SCALAR {
    return 'hallo';
}

sub drei : LIST {
    return (1,2,3);
}

1;


Code: (dl )
1
2
3
4
5
6
7
8
CheckTest::test(); # 'hallo'
my $test = CheckTest::test(); # sub have to be called in void context at CheckContext.pm line 17.
my @test = CheckTest::test(); # sub have to be called in void context at CheckContext.pm line 17.


my $zwo = CheckTest::zwo();
my @zwo = CheckTest::zwo(); # sub have to be called in scalar context at CheckContext.pm line 33.
CheckTest::zwo(); # sub have to be called in scalar context at CheckContext.pm line 33.


mit caller könnte man die Fehlermeldung noch besser gestalten...
OTRS-Erweiterungen (http://feature-addons.de/)
Frankfurt Perlmongers (http://frankfurt.pm/)
--

Unterlagen OTRS-Workshop 2012: http://otrs.perl-services.de/workshop.html
Perl-Entwicklung: http://perl-services.de/

View full thread Automatisches Warning bei falschem Kontext für Funktion