The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

calling functions in perl

I have some validation functions in a perl script named 'validateQuestion1', 'validateQuestion2', etc. There is/will be a fixed number of these functions, so is there a way to set up a for-loop to call all of them without having to explicitly call each one in turn?
Friday, April 08, 2005
validateQuestion(int questionNumber)

Friday, April 08, 2005
You can stuff references to the functions in an array and call them in turn.

my @funcs = (\&func1, \&func2, \&func3);

foreach my $func (@funcs) {
comp.lang.c refugee
Friday, April 08, 2005
does Perl have an eval function that can process a string containing Perl?

You create your function calls as strings, then eval them...
Friday, April 08, 2005
Perl does have an eval function (called eval, imagine that) which could be used to do what you describe. However, I think the function pointer method is cleaner.
comp.lang.c refugee
Friday, April 08, 2005
Thanks to everyone who responded.
Saturday, April 09, 2005
Get yourself a copy of this book.
Learning Perl Objects, References & Modules
full name colon
Saturday, April 09, 2005
>does Perl have an eval function that can process a string containing Perl?

Yes it does, so that the OP could have something like:

foreach (1..$numberOfFunctions) {
    eval "function$_()";

The eval takes the string and runs it as Perl code, and $_ is the argument of the foreach loop as it runs through the range given above.

Alternatively, it would be possible to look in the symbol table and find all functions of a particular type, such as "function\d+", which would find function1, function99934983, etc, and invoke them each in turn.

Sunday, April 10, 2005
Oh, and email me if you have any questions on the eval.

That is code off the top of my head, not really tested but I have used techniques like that in the past.
Perl Semi-Guru Send private email
Sunday, April 10, 2005
Something like

for (1..5) { ${validate$_}->(); }

Check out the perl object documentation and read about closures. "Effective Perl Programming" could also be useful.
Friday, April 22, 2005

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
Powered by FogBugz