zaebst has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I've always had a problem with getting my modules to pass their subroutines as callbacks. Does anyone know the correct structure?

package WebUtil; sub Gen_HTML { my $self = shift; # # Do stuff to make html $self->{$HTML} .= qq( html content stuff ); return($self->{$HTML}); } sub run_pjx { my $self= shift; my $pjx = new CGI::Ajax( 'exported_func' => sub { my $in = shift; return("Changed +Main $in\n"); }, 'skip_header' => 1 ); my $ref_Gen_HTML = sub { $self->Gen_HTML() }; print $pjx->build_html( $self->{$WU_CGI} , &$ref_Gen_HTML ); #note should be: build_html( $cgi_object, \&callback_Function ); }

Replies are listed 'Best First'.
Re: Object Oriented Callback
by ikegami (Patriarch) on Dec 17, 2008 at 05:31 UTC
    &$ref_Gen_HTML is a (special form of) subroutine call. You want to pass the reference, $ref_Gen_HTML.
    my $ref_Gen_HTML = sub { $self->Gen_HTML() }; print $pjx->build_html( $self->{$WU_CGI}, $ref_Gen_HTML );
    or just
    print $pjx->build_html( $self->{$WU_CGI}, sub { $self->Gen_HTML() } );

    Please use <c>...</c> instead of <pre>...</pre> on PerlMonks.

Re: Object Oriented Callback
by kennethk (Abbot) on Dec 17, 2008 at 05:52 UTC
    In addition to ikegami's wonderful advice, you should also be including use strict; and use warnings; to catch simple headaches. There's some reference material you may find valuable in perlref on callbacks (search term coderef). To store a code reference in a hash and call it, you can do the following:

    my %hash = (code => sub{print 'x'}); &{$hash{code}};

      Thanks guys. After fixing the subroutine call, I found one more problem and got things working. I switched pre tags to c tags as well.