question about variable procedure call

A

Alexandre Jaquet

Hi I currently try to optimize an application and I got the following
question.

How in perl can I call call variable procedure call.

I want to delete code like that :

if ($var = something) { doThat()

if ($var = other) ( doOther

if

to $routine = $var_name
call routine

any idea thanx
 
D

Dominik Seelow

Alexandre said:
Hi I currently try to optimize an application and I got the following
question.

How in perl can I call call variable procedure call.

I want to delete code like that :

if ($var = something) { doThat()

if ($var = other) ( doOther

if

to $routine = $var_name
call routine

any idea thanx


Hello Alexandre,

I suggest to use a hash storing sub references:

use strict;
my $var_name='subA';
my %subs = (
subA =>sub { print 'A'},
subB =>sub { print 'B'}
);
foreach my $var_name (qw (subA subB subC)){
&{$subs{$var_name}} if ref $subs{$var_name} eq 'CODE';
}

This will allow you to check whether a sub exists before you call it.

But I'm not sure that this really optimises your code. I prefer if/elsif
constructions.

Cheers,
Dominik
 
A

Arndt Jonasson

Alexandre Jaquet said:
Hi I currently try to optimize an application and I got the following
question.

How in perl can I call call variable procedure call.

I want to delete code like that :

if ($var = something) { doThat()

if ($var = other) ( doOther

if

to $routine = $var_name
call routine

Your own example isn't even correct Perl, so I'm guessing what it is
you want.

Do you know that this change will make the program faster?

Maybe this is something like what you want:

sub apa {
my $r = shift;
$r * 2;
}

sub banan {
my $r = shift;
$r + 2;
}

$f = \&apa;
$x = &$f (5);

You could map the values of $var to the correct function reference via
a hash table.
 
B

Brian McCauley

my %subs = (
subA =>sub { print 'A'},
subB =>sub { print 'B'}
);

Surley to match the OP this should be:

my %subs = (
something => \&doThat,
other => \&doOther,
);

&{$subs{$var_name}} if ref $subs{$var_name} eq 'CODE';

The OP example did noy share the current @_ with the called subroutine
so it would be more ideomatic as:

$subs{$var_name}->() if $subs{$var_name};

Note: I've simplified the condition. There is no legitmate way a value
other than a CODEref could have got into %subs. If, somehow, one has it
is better that the program fall over rather than silently ignore
something that can only indicate a bug in the program.

(ISTR the -> is optional in recent Perl but I think this is one case I'd
keep it).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top