+ give me a fortune cookie
- Your fortune cookie: &fortune()
And that would, of course, be the equivalent to the now-system of having a Perl subroutine and calling a method to the module to associate an object with that routine.
However I can't seem to figure out how to take a scalar that contains Perl code as its value, and make a subroutine with its data as its code.
print "Creating a coderef...\n";
my $refs = {};
$refs->{code} = sub {
$subroutine
};
print "Coderef Value: $refs->{code}\n\n";
print "Calling subroutine...\n\n";
my $out = &{$refs->{code}} ("myMethod", "someData");
print "Done. Out = $out\n";
And its output was this:
Quote:
D:\Perl\tests\Optional Regexp>perl subs.pl
My Subroutine's Source Code:
my ($method,$data) = @_;
return "Method = $method; Data = $data";
===========================
Creating a coderef...
Coderef Value: CODE(0x234fe0)
Calling subroutine...
Done. Out =
my ($method,$data) = @_;
return "Method = $method; Data = $data";
The coderef value test worked and gave me a coderef but what the subroutine should have returned was the values of $method and $data, rather than the entire subroutine's code.
Does anybody know how to do this?
edit
One thing that worked as a solution to my very simply test,
Code:
$refs->{code} = sub {
return eval $subroutine;
};
Did not work in RiveScript. I might be on the right track though. I've tried do and return do also, which both failed.
edit(2)
I also tried evaling the entire thing (setting the coderef and all)...
Code:
my $val = eval "
$self->{macros}->{'$objName'} = sub {
$objCode
};
$self->{macros}->{'rive'} = sub {
return 'Rive macro success';
};
1;
";
print "Eval: $val\n";
The eval returns undef like it should when it's successful but neither the code-defined object or the 'rive' object were defined at all. _________________ Current Site (2008) http://www.cuvou.com/
If you can name your sub, then this might help you:
Code:
my $eval_string = 'sub hello { print "hello\n"; }';
eval $eval_string;
&hello;
If you have to use a coderef, then this might help (although I couldn't make $sub a my value):
Code:
my $eval_string = '$sub = sub { print "hello\n"; }';
eval $eval_string;
&$sub;
I left out the part where you take your sub contents from a text file and add them to $eval_string, since I figured you know all about that. If not, I could rework this to be more complete.
Thanks. One solution I figured out that *kinda* works was to use eval to create a new subroutine with its contents, then call the $self->setSubroutine method to associate the subroutine with its object. So basically it took the Perl code from the reply file and did with it the exact same thing you'd do before I got the bright idea to do this.
The only problem was that some objects wouldn't work. Like my weather, Google, and botmaster command objects wouldn't be created this way. It might be something to do with the variables they used but I'm not sure. _________________ Current Site (2008) http://www.cuvou.com/