Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How to call a function in Object Oriented?

stephenlimstephenlim Member Posts: 20
Could anyone help me to figure out how to pass a function to another module and call from there? To be described in more clearer, here is the example problem.

use package difMod;

sub fun1() { ... }

package main;
...
difMod->configure(
SubHeader => &fun1; #it is passing as a Hash form.
);
...

============================

package difMod;
...
sub configure() {
$self = shift;
#How should i call the passed function here?
}
...

============================

Thanks! :)

Comments

  • JonathanJonathan Member Posts: 2,914
    : Could anyone help me to figure out how to pass a function to another
    : module and call from there? To be described in more clearer, here is
    : the example problem.
    :
    : use package difMod;
    :
    : sub fun1() { ... }
    :
    : package main;
    : ...
    : difMod->configure(
    : SubHeader => &fun1; #it is passing as a Hash form.
    : );
    : ...
    That looks OK, but I'm curious why you put sub fun1() {...} outside of the main package. It will go into package main anyway unless you've hidden some other stuff further up the script. Or you've defined it in a seperate package, but I doubt it otherwise the function will probably be out of scope for passing.

    : ============================
    :
    : package difMod;
    : ...
    : sub configure() {
    : $self = shift;
    : #How should i call the passed function here?
    : }
    : ...
    :
    : ============================
    Try something like this:-

    [code]sub configure() {
    #Get invocant.
    $self = shift;

    #Get data passed.
    my %input = @_;

    #Call the sub.
    &{$input{'SubHeader'}};
    }[/code]

    You need to dereference the reference. I think I've made a spelling mistake there. :-) I believe (but haven't checked) that you need to put the $input{'SubHeader'} inside another set of {...} so that the entire value gets interpolated. Otherwise the & may bind only to $input, which wouldn't have the desired effect. I don't know that it would, but it's best to be safe.

    You probably know most of it already, but you want to check out my intro to doing OOP in Perl:-
    http://www.jwcs.net/~jonathan/perloop.htm

    Hope this helps. If anything I've written is totally wrong, it's because I've just had a physics exam. ;-)

    Jonathan

    ###
    # Example Of Perl 6 Syntax.
    push @will, my Power $button;
    my $hardware is Useless but Valuable;
    do ($nothing) while $i.work and print $stuff;
    push (@will, my Off $button) and die "with me";

Sign In or Register to comment.