[asterisk-users] Asterisk Tips and Tricks: Dynamic Subroutines inAGI

Watkins, Bradley Bradley.Watkins at compuware.com
Fri Aug 29 06:47:07 CDT 2008


> -----Original Message-----
> From: asterisk-users-bounces at lists.digium.com 
> [mailto:asterisk-users-bounces at lists.digium.com] On Behalf Of 
> Darren Sessions
> Sent: Thursday, August 28, 2008 10:12 PM
> To: Asterisk Users Mailing List - Non-Commercial Discussion
> Subject: [asterisk-users] Asterisk Tips and Tricks: Dynamic 
> Subroutines inAGI
...
> The hurdle in doing something like this was how to 
> dynamically execute  
> a subroutine from the results of the database query which 
> were dumped  
> into a variable. The method I used with the subroutine reference  
> doesn’t allow for arguments to be passed (if anyone finds / knows a  
> way to do this, let me know), so I use global variables.
> 
> This is a simple example of dynamic subroutine execution 
> (without the  
> database query):
> 
> use strict;
> use warnings;
> 
> our $called_number;
> our $calling_number;
> 
> sub run_me {
>    $AGI->verbose(”Called Number = “.$called_number, 1);
>    $AGI->verbose(”Calling Number = “.$calling_number, 1);
> }
> 
> sub set_variables {
>    $called_number = “8005551212″;
>    $calling_number = “3002221111″;
> }
> 
> sub dynamic_execute {
>    my ($sub) = @_;
>    if (!$sub) {
>      $AGI->verbose(”No subroutine name passed!!”, 1);
>      return(-1);
>    }
>    my $exec = ¥&{$sub};
>    return($exec->());
> }
> 
> set_variables();
> dynamic_execute(”run_me”);

If you don't mind disabling strict refs (no strict 'refs';), you could easily do this.

This would allow you to use something like: &$sub($argument1, $argument2);

The only other way I can think of (though I have not tried it) would be to populate a hash with subroutine refs and use the string as the index into it.  
Something like this:

#!/usr/bin/perl

use strict;
use warnings;
sub print_ref { print @_; };

my %sub_hash = ("print_ref", ¥&print_ref);

sub print_stuff {
        my $sub = shift;
        my $string = shift;
        &$sub($string);
}

print_stuff($sub_hash{"print_ref"}, "This is printed.¥n");



The first idea uses the symbol table directly, and the second one essentially is building your own symbol table.

Hope that helps,
- Brad



More information about the asterisk-users mailing list