For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > February 2006 > passing subroutine function as a variable









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author passing subroutine function as a variable
John

2006-02-21, 7:55 am

Hi,

I am beginner, so this may have easy solution.

I have got finished subroutine which works fine when I call it as
subname(var_a,var_b).

Then I have got another subroutine subname2(var2_a,var2_b) and I would
like to pass first subroutine as a variable:

$variable='subname(var_a,var_b)';

subname2($variable,var2_b) {
my ($variable,$y)=@_;
if ($variable ne 0) { $variable;}
}

This should pass my first subroutine 'subname(var_a,var_b)' as a
variable and run it inside the second sub.

It doesn't work, the variable is passed but it is not run. How could I
do this in other way, what should I change?


Thanks a lot for any help.

-John

Paul Lalli

2006-02-21, 6:57 pm

John wrote:

> I am beginner, so this may have easy solution.
>
> I have got finished subroutine which works fine when I call it as
> subname(var_a,var_b).


No you don't. Perl variables start with a $, @, or %.

Post real code.

>
> Then I have got another subroutine subname2(var2_a,var2_b) and I would
> like to pass first subroutine as a variable:
>
> $variable='subname(var_a,var_b)';


This is a string, not a subroutine.

>
> subname2($variable,var2_b) {


This doesn't do anything close to what you think it does. If you
didn't get the "illegal characters in prototype" warning here, you need
to stop coding without `use warnings;` immediately.


> my ($variable,$y)=@_;
> if ($variable ne 0) { $variable;}


I don't have a clue what you think these are supposed to do. Again,
you should be enabling warnings.


> }
>
> This should pass my first subroutine 'subname(var_a,var_b)' as a
> variable and run it inside the second sub.
>
> It doesn't work, the variable is passed but it is not run. How could I
> do this in other way, what should I change?


Pass the subroutine, not a string that happens to match the name of a
subroutine.

sub2(\&sub1, $var1, $var2);

sub sub2 {
my $sub_to_run = shift;
print "About to call passed-in sub with arguments: @_\n";
$sub_to_run->(@_);
}

Paul Lalli

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com