Thread Prüfung, ob Konstante definiert wurde (14 answers)
Opened by TheMic at 2012-08-02 12:16

pq
 2012-08-02 13:53
#160505 #160505
User since
2003-08-04
12208 Artikel
Admin1
[Homepage]
user image
2012-08-02T11:41:25 Muffi
Achja, das can ohne Vererbung müsst dann
Code (perl): (dl )
if (UNIVERSAL::can(__PACKAGE__, 'KONSTANTE'))

sein.

bist du dir sicher?

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
use strict;
use warnings;
use v5.010;


package PARENT;

use constant PARENT_ONLY => 23;
use constant BOTH => 42;

package CHILD;

use base 'PARENT';
use constant CHILD_ONLY => 99;
use constant BOTH => 42.1;

for my $name (qw/ PARENT_ONLY BOTH CHILD_ONLY /) {
    if (my $coderef = __PACKAGE__->can($name)) {
        my $result = $coderef->();
        say "CHILD->can($name), result=$result";
    }
    if (my $coderef = UNIVERSAL::can(__PACKAGE__, $name)) {
        my $result = $coderef->();
        say "UNIVERSAL::can(CHILD, $name), result=$result";
    }
}


Code: (dl )
1
2
3
4
5
6
CHILD->can(PARENT_ONLY), result=23
UNIVERSAL::can(CHILD, PARENT_ONLY), result=23
CHILD->can(BOTH), result=42.1
UNIVERSAL::can(CHILD, BOTH), result=42.1
CHILD->can(CHILD_ONLY), result=99
UNIVERSAL::can(CHILD, CHILD_ONLY), result=99


alle methoden werden gefunden, auch die im PARENT, egal welche variante von can() man aufruft.
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. -- Damian Conway in "Perl Best Practices"
lesen: Wiki:Wie frage ich & perlintro Wiki:brian's Leitfaden für jedes Perl-Problem

View full thread Prüfung, ob Konstante definiert wurde