in reply to Dynamically generating function callbacks

In addition to the questions raised in the first reply, I'm was wondering about this part:

Is there anyway to dynamically generate these functions during compile-time so that I can just create an array...

As BrowserUk mentioned, it's easy to write perl code that will create new subroutines at run-time, but I'm not sure what it means to create subs dynamically at compile-time. My understanding is that the latter simply doesn't happen (unless you get into evil things like code filters...) ... and AnonyMonk's reply below has cleared this up for me. (Thanks, AM! -- I had forgotten about that attribute of the BEGIN block. But now I'm still wondering if that's what the OP really wants.)

Here's an example that might help, but since it's as vague as the snippets originally shown in the OP, it might confuse rather than illuminate, and/or might not resemble what you're trying to accomplish...

#!/usr/bin/perl use strict; use warnings; sub callback_reply { print "callback_reply got " . scalar @_ . " args: @_\n\n"; } my ( %callback_sub, %callback_wrapper ); for my $i ( 1 .. 4 ) { my $subname = "function_$i"; $callback_sub{$subname} = sub { print "args passed to $subname: @_\n"; my $err_value = ( rand > 0.5 ) ? 1 : 0; my $rtn_value; $rtn_value += $_ for ( @_ ); return ( $err_value, $rtn_value ); }; $callback_wrapper{$subname} = sub { my ( $cb_id, @params ) = @_; my ( $_err, $cb_data ) = $callback_sub{$subname}->( @params ); callback_reply( $cb_id, $_err, $cb_data ); return $_err; } } for my $i ( 1 .. 4 ) { my @parms; for my $j ( 0 .. 1 + int( rand( 4 ))) { push @parms, sprintf( "%5.3f", $i + rand ); } printf( "Calling wrapper %d with %d params: %s\n", $i, scalar @parms + 1, "$i @parms" ); $callback_wrapper{"function_$i"}->( $i, @parms ); }
(updated subroutine creation loop to use $subname instead of repeating "function_$i" throughout the loop)

Replies are listed 'Best First'.
Re^2: Dynamically generating function callbacks
by Anonymous Monk on Nov 09, 2011 at 08:59 UTC