Thread Instanzmethode von pkg A in pkg B mit Objekt von A aufrufen (16 answers)
Opened by styx-cc at 2017-08-03 23:30

styx-cc
 2017-08-03 23:30
#187087 #187087
User since
2006-05-20
533 Artikel
BenutzerIn

user image
Hi.

Folgender Code:
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
#!/usr/bin/perl -w
use strict;

my $a = new A();
$a->pass_sub();


package A;
use B;

sub new {
    my ( $class, ) = @_;

    my $self  = { };
    bless $self, ref($class) || $class;

    return $self;
}

sub pass_sub {
    my ( $self, ) = @_;

    $self->{'sub_handler'} = new B();
    $self->{'sub_handler'}->use_sub_later( sub { $self->say_hello } );
}

sub say_hello {
    my ( $self, ) = @_;
    print "Hello! Args: ". join(',', @_) ."\n";
}

1;


package B;

sub new {
    my ( $class, ) = @_;

    my $self  = { };
    bless $self, ref($class) || $class;

    return $self;
}

sub use_sub_later {
    my ( $self, $sub, ) = @_;

    my $ready_to_use = 1;
    $sub->('ARG1', 'ARG2') if $ready_to_use;
}

1;


Ausgabe:
Code: (dl )
1
2
perl test.pl 
Hello! Args: A=HASH(0x1d28088)


Wie muss ich (vermutl.) Zeile 24 anpassen, damit er mir auch die Argumente mit ausgibt (ARG1, ARG2)?
Ist das prinzipiell schlechter Stil?

Oder bin ich gezwungen, dass Objekt aus Package A als Argument an use_sub_later mitzugeben?

Code: (dl )
$self->{'sub_handler'}->use_sub_later($self, \&say_hello ); 


Lieben Gruß.
Pörl.

View full thread Instanzmethode von pkg A in pkg B mit Objekt von A aufrufen