Command Line

G

George Kinley

Hi
I need to call a subroutine in a perl program but the name of the
subroutine I want to pass as command line argument ,
is this possible if yes then how
 
B

Brian McCauley

George Kinley said:
Subject: Command Line

Please put the subject of your post in the Subject of your post. If
in doubt try this simple test. Imagine you could have been bothered
to have done a search before you posted. Next imagine you found a
thread with your subject line. Would you have been able to recognise
it as the same subject?
I need to call a subroutine in a perl program but the name of the
subroutine I want to pass as command line argument ,
is this possible if yes then how

This can be done directly using a symbolic function reference.

It can also be done less directly using eval().

See:
perldoc perlref
prelfoc -f eval

However you should consider instead using a dispatch table.

For how to do so and why this is often prefereable see numerous
previous threads on this exact same subject.

http://groups.google.com/groups?q=dispatch+table&meta=group=comp.lang.perl.misc

--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
 
S

Sherm Pendley

I need to call a subroutine in a perl program but the name of the
subroutine I want to pass as command line argument ,
is this possible if yes then how

Two possibilities come to mind:

You could build up a string with the function call in it, and then eval()
that string:

my $result=eval("$function_name()");

Or, you could call the function via a symbolic reference:

no strict 'refs';
my $result=&{$function_name}();

see 'perldoc -f eval' and/or 'perldoc perlref' for details.

sherm--
 
A

Ash

Hi ,
thanks it worked
Sherm Pendley said:
Two possibilities come to mind:

You could build up a string with the function call in it, and then eval()
that string:

my $result=eval("$function_name()");

Or, you could call the function via a symbolic reference:

no strict 'refs';
my $result=&{$function_name}();

see 'perldoc -f eval' and/or 'perldoc perlref' for details.

sherm--
 
U

Uri Guttman

SP> Two possibilities come to mind:

both are horrible and dangerous and not needed.

have you ever read any of the myriad of threads on this subject? in
almost all cases these answers are not good for you or your children.

SP> You could build up a string with the function call in it, and then eval()
SP> that string:

SP> my $result=eval("$function_name()");

SP> Or, you could call the function via a symbolic reference:

SP> no strict 'refs';
SP> my $result=&{$function_name}();

first, the symbol table is just a special hash tree with some odd (but
critical) side effects. so why would you want to use such a specialized
tree for basic data structures such as this?

search google groups for 'dispatch tables'. it has been covered here
many times. i was waiting for someone else who has learned them to post
and answer. and i was hoping to not see these two evil solutions.

SP> see 'perldoc -f eval' and/or 'perldoc perlref' for details.

if you have read those, wipe out that set of brain cells and read up on
dispatch tables. don't learn symrefs or eval until you have learn enough
perl to know when to not use those calls. then you will be able to use
them when needed. i have yet to see a newbie come even close to really
needing them. they always use them for data structures even if they
don't know it.

uri
 
S

Sherm Pendley

SP> Two possibilities come to mind:

both are horrible and dangerous and not needed.

have you ever read any of the myriad of threads on this subject?

No, actually I've been away from usenet for quite a while.

I can imagine some complications - there are security issues if you don't
check the incoming sub name carefully, and you'll want to verify that the
requested sub exists, of course. Nothing I'd describe as "horrible,"
although I'll concede that it might be dangerous in the hands of a newbie,
or someone for whom defensive & secure programming isn't normal practice.

Still, I'll do some Googling on those past threads you mentioned, to see
if there's something truly horrible that I missed. Thanks for the tip.
search google groups for 'dispatch tables'.

Something like this?

my $disp = {
'foo' => \&foo,
'bar' => \&bar,
'baz' => sub { return 'baz'; },
};
my $funcName = 'foo';
my $result = &$disp->{$funcName};

That's useful if you want to limit the caller to a known set of "approved"
functions. But nothing in the OP's question indicated a desire/need to
limit the functions that could be called. I simply assumed he was aware of
the consequences of executing arbitrary code, and answered the question as
given.

In hindsight, I think you're right - a caveat was in order, and a safer
option that's preferred whenever it isn't too restrictive.
if you have read those, wipe out that set of brain cells

I'd love to, but I don't think Pink Floyd is ever going to tour again. ;-(

sherm--
 
K

ko

[snip dispatch table vs. eval() and symbolic reference...]
Something like this?

my $disp = {
'foo' => \&foo,
'bar' => \&bar,
'baz' => sub { return 'baz'; },
};
my $funcName = 'foo';
my $result = &$disp->{$funcName};
---------------^^-----------------
syntax error

You probably knew this :), but '&$' is done before anything else, which
treats $disp as a code reference, not an anonymous hash reference. To
call the sub:

my $result = $disp->{$funcName}->();

Or you could uses braces...

[snip]

HTH - keith
 
U

Uri Guttman

SP> No, actually I've been away from usenet for quite a while.

SP> I can imagine some complications - there are security issues if
SP> you don't check the incoming sub name carefully, and you'll want
SP> to verify that the requested sub exists, of course. Nothing I'd
SP> describe as "horrible," although I'll concede that it might be
SP> dangerous in the hands of a newbie, or someone for whom defensive
SP> & secure programming isn't normal practice.

if you don't feel those possibilities are horrible, then you shouldn't
be answering stuff here. this is obviously a newbie and just the type to
not tell about symrefs and eval. we have a group rule about not doing
that. they don't need those techniques (in fact very few do) and they
are inherently dangerous. even if this script is isolated and run only
by this kid, he will learn a technique early on and will use again and
again. his brane is now infected with mad perl code disease.

SP> Something like this?

SP> my $disp = {
SP> 'foo' => \&foo,
SP> 'bar' => \&bar,
SP> 'baz' => sub { return 'baz'; },
SP> };
SP> my $funcName = 'foo';
SP> my $result = &$disp->{$funcName};

SP> That's useful if you want to limit the caller to a known set of
SP> "approved" functions. But nothing in the OP's question indicated a
SP> desire/need to limit the functions that could be called. I simply
SP> assumed he was aware of the consequences of executing arbitrary
SP> code, and answered the question as given.

never just answer a newbie question as a given. this is true for all
teaching to young ones. they usually don't know enough to ask the right
questions let alone figure out the answers. most times they have no
understanding of the evils of things and are just happy to get it
working. notice the OP (under a different name?!) responded to your post
with a 'it works' comment. so he is using one of your answers. and i
doubt he will be reading the rest of this thread.

SP> In hindsight, I think you're right - a caveat was in order, and a
SP> safer option that's preferred whenever it isn't too restrictive.

that was my point. or better, never mention them unless the situation
warrants it. brian did mention both and then showed a basic dispatch
table. i should rebuke him for even showing those first. newbies seem to
like the concept of symrefs as it satisifies their craving for something
that works and who cares about any side effects. they don't realize the
symtable is just a special and dangerous hash tree and so why not use a
regular data structure - the dispatch table. most don't know about hard
refs or code refs and using hashes for verifying entry data (one of the
nice side effects of dispatch tables) is also a new concept to most.

SP> I'd love to, but I don't think Pink Floyd is ever going to tour
SP> again. ;-(

i have totally forgotten the july 3, 1977 concert in madison square
garden where they did all of animals and all of wish you were here with
amazing synchronized animation and effects. encore were a few songs from
dark side. i wish i was still there. :)

uri
 
B

Brian McCauley

Uri Guttman said:
this is obviously a newbie and just the type to not tell about
symrefs and eval. we have a group rule about not doing that.

I am not part of 'we' on this. I think it is better to tell people
about the dangers of doing what it is that they think they want to do.

If we don't mention that they can simply do what they said then sooner
or later they'll discover that they can. When this happens they'll
think they've found a better solution that we didn't know about.

This in turn means that they'll be more (not less) likely to suffer
"mad perl code disease" in the long run. And worse still they'll
become inclined to distrust us a source of good advice.

Anyhow this CS-centric view of Perl irritates me as much as it does
MJD. (You did catch his rant at YAPC::Europe::2003 didn't you, Uri).

--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
 
U

Uri Guttman

BM> I am not part of 'we' on this. I think it is better to tell
BM> people about the dangers of doing what it is that they think they
BM> want to do.

i didn't object to yours as much as sherm's since you did put a caveat
with it. i just would have written a more viscious caveat or just not
mentioned it when really appropriate. speaking of which, i would love to
see a list of posts here where using symrefs or eval were the right
solutions to problems. we rarely see them since those who know what they
do and why, write code with that in mind. i use symrefs for special
exporting or AUTOLOAD stuff. i use eval to load perl data structures
from files. these are places where those funcs are the only good answer.

BM> If we don't mention that they can simply do what they said then
BM> sooner or later they'll discover that they can. When this happens
BM> they'll think they've found a better solution that we didn't know
BM> about.

the docs for them need to state this message. use these only when they
are the proper solution, not when something safer can be used. then the
pitfalls of using them should be mentioned. then common ways to avoid
them (dispatch tables, proper perl data structures) should be mentioned
with links to perllol, perldsc and the vapordoc perldispatchtable. are
dispatch tables covered in the faq? i don't ever recall seeing that in
there.

BM> This in turn means that they'll be more (not less) likely to suffer
BM> "mad perl code disease" in the long run. And worse still they'll
BM> become inclined to distrust us a source of good advice.

BM> Anyhow this CS-centric view of Perl irritates me as much as it does
BM> MJD. (You did catch his rant at YAPC::Europe::2003 didn't you, Uri).

and i ranted about this in my talk there. :)

and i am not being CS-centric in any of my rants. i just express my 30
years of coding experience which tells me what is good and bad. there
are plenty of academic things i find so useless and perl does them a
better way. can you lisp lisp? :)

uri
 
A

Anno Siegel

Uri Guttman said:
[...]

SP> I can imagine some complications - there are security issues if
SP> you don't check the incoming sub name carefully, and you'll want

[lots snipped to get to this]
newbies seem to
like the concept of symrefs as it satisifies their craving for something
that works and who cares about any side effects.

I have also wondered why beginners seem to love symrefs so much (and
string eval). I believe there's more to it than a newbie's greed for
a quick success.

Beginning programmers are confused and frustrated by the different
behaviors a computer shows them, once they look behind the unifying UI.
One of the significant differences is the machine's response to program
text, as opposed to other data. "It *knows* the variable name, so why
can't I type in the name and have it print the value?" is a legitimate
question at some stage, and the short answer is, "Because what you type
is data, and the variable is part of the program."

Now, Perl has means to bridge the gap between data and program, most
prominently "eval" and symrefs. It is exactly that they turn data into
program text what makes them potential hazards. The gap is there for
our protection, not only from malicious users, but from a maze of
cross-dependencies that would make sane programming impossible.

John von Neumann kicked off modern programming by observing that program
and data could be stored using the same techniques and media. Modern
programmers made it their task to create a gap between them, as
impenetrable and separating as possible while still putting von Neumann's
invention to use. They had to, the other way lies madness. And Lisp.

Anno
 
P

pkent

Two possibilities come to mind:
....

and I add a third: dispatch tables - build one like this

my %dt = (
bake => \&do_bake,
freeze => \&do_freeze,
);

# and then define your routines...
sub do_bake {
# do stuff
}


and then use the string 'bake' to retrieve the code reference like this:

my $str = 'bake';
my $routine = $dt{$str} || die "Cannot find code for $str";
$routine->(@arguments);

P
 
P

pkent

Brian McCauley said:
This in turn means that they'll be more (not less) likely to suffer
"mad perl code disease" in the long run. And worse still they'll

Parsed as 'mod perl code disease' and I wondered what it was. An
assumption that you could use in-memory caching? An idea that compile
time is a one-off hit? A vehement desire to not use exit()?

P
 
U

Uri Guttman

AS> I have also wondered why beginners seem to love symrefs so much (and
AS> string eval). I believe there's more to it than a newbie's greed for
AS> a quick success.

AS> Beginning programmers are confused and frustrated by the different
AS> behaviors a computer shows them, once they look behind the unifying UI.
AS> One of the significant differences is the machine's response to program
AS> text, as opposed to other data. "It *knows* the variable name, so why
AS> can't I type in the name and have it print the value?" is a legitimate
AS> question at some stage, and the short answer is, "Because what you type
AS> is data, and the variable is part of the program."

good analysis. still hard to explain to newbies why separating code and
data is a good thing.

AS> John von Neumann kicked off modern programming by observing that
AS> program and data could be stored using the same techniques and
AS> media. Modern programmers made it their task to create a gap
AS> between them, as impenetrable and separating as possible while
AS> still putting von Neumann's invention to use. They had to, the
AS> other way lies madness. And Lisp.

lisp's official name is mad perl code disease. :)

uri
 
D

David K. Wall

Anno Siegel said:
I have also wondered why beginners seem to love symrefs so much (and
string eval). I believe there's more to it than a newbie's greed for
a quick success.

Beginning programmers are confused and frustrated by the different
behaviors a computer shows them, once they look behind the unifying UI.
One of the significant differences is the machine's response to program
text, as opposed to other data. "It *knows* the variable name, so why
can't I type in the name and have it print the value?" is a legitimate
question at some stage, and the short answer is, "Because what you type
is data, and the variable is part of the program."

/me plays devil's advocate, or maybe argumentative newbie...

Yeah, so? That's not an answer, that's a restatement of the problem.
Data, program, it's all in the computer and I should be able to access any
of it. Don't give me this crap about them being different. If I tell the
computer I want foo, then it should give me what's in $foo! (that's NOT
supposed to be $foo factorial)
Now, Perl has means to bridge the gap between data and program, most
prominently "eval" and symrefs. It is exactly that they turn data into
program text what makes them potential hazards. The gap is there for
our protection, not only from malicious users, but from a maze of
cross-dependencies that would make sane programming impossible.
John von Neumann kicked off modern programming by observing that program
and data could be stored using the same techniques and media. Modern
programmers made it their task to create a gap between them, as
impenetrable and separating as possible while still putting von Neumann's
invention to use. They had to, the other way lies madness. And Lisp.

Quote! (adds to quote file)
 
G

Gunnar Hjalmarsson

Uri said:
this is obviously a newbie and just the type to not tell about
symrefs and eval. we have a group rule about not doing that. they
don't need those techniques (in fact very few do) and they are
inherently dangerous. even if this script is isolated and run only
by this kid, he will learn a technique early on and will use again
and again. his brane is now infected with mad perl code disease.

Hi Uri,

I consider me to be a newbie that happens to have an idea of what you
are talking about. If I had been totally clueless, I would have been
either insulted by your comment above, or at least you'd have aroused
my curiosity. In any case, the effect of your comment would have been
the opposite of what you intended.

As regards the group rule, I must have missed it when reading the
posting guidelines.

Most readers of this group, whether newbies or not, are grown-up people.
 
G

Gunnar Hjalmarsson

Uri said:
i was more upset about the posting of the evil answers with no
caveat

I realize that.
than the newbie actually seeing it. he is one person

More than one newbie will read your post, Uri.
but the bad answer is archived in google for others to see.

The "bad answer" is also available in the Perl documentation, in the
Camel book, etc... Don't undervalue the readers!
the regulars have always encouraged dispatch tables over
symrefs/eval.

I have noticed that. :) And I appreciate that you have taken the time
to repeatedly explain it. I have learned from some of those treads.
Thanks!
this is definitely material for an FAQ (or several).

Sure, why not?
GH> Most readers of this group, whether newbies or not, are
GH> grown-up people.

true, but coding experience is the key.

I would disagree. Judge is the key. Grown-up people, unlike kids (i.e.
young people), are assumed to be able to make well-considered
decisions. They are assumed to have the judge to do what's best for them.
newbies will not know enough to not hurt themselves. think of it as
childproofing your coding environment. don't allow them near the
drano until they know what drano is and isn't for. drano will clean
anything ya know but it is really meant for drains. same with
symrefs/eval. they CAN do anything but are meant for the tough
problems that only they can solve. don't use drano to wash your
hands. :)

hmm, i like that analogy. any thoughts?

No further comments.
 
U

Uri Guttman

GH> Uri Guttman wrote:

GH> Most readers of this group, whether newbies or not, are
GH> grown-up people.
GH> I would disagree. Judge is the key. Grown-up people, unlike kids
GH> (i.e. young people), are assumed to be able to make
GH> well-considered decisions. They are assumed to have the judge to
GH> do what's best for them.

you are assuming the chronological and emotional and technical ages of
coders are related where i say they are not. i have seen all sorts,
kiddies who got it right off, long time coders who never did get it and
all across the spectrum. but on average, new coders (of any age) tend to
go down the wrong paths until something (a book, teacher, posting,
whatever) points them in the right direction.

so childproofing is important. sure you can code kiddie perl (no strict,
warnings, c style, etc.) and get away with it. same with symrefs/eval
but we know all of those will bite them eventually. so we try to guard
them against those evils. now the camel and other books tend to be too
reference oriented and show everything. i did a tech edit job on the
'core perl' book and i requested the author to remove a symref section
from his early overview. symrefs are so rarely needed and so potentially
dangerous (very little code and mostly core modules mung the symbol
table use them) that they should not be in any perl overview or intro.

too bad the autofaq is shut off and no one is taking edits and
such. this is definitely due for inclusion. i see it too often.

uri


Uri Guttman ------ (e-mail address removed) -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org
 
B

Ben Morrow

Uri Guttman said:
AS> Beginning programmers are confused and frustrated by the different
AS> behaviors a computer shows them, once they look behind the
AS> unifying UI.

Which is the advantage of Unix: it doesn't have a unifying UI.
[Not that this comment belongs here, of course :) ]
good analysis. still hard to explain to newbies why separating code and
data is a good thing.

How about pointing out that M$'s inability to appreciate that fact is
what leads to the current problem of viruses?
lisp's official name is mad perl code disease. :)

c.f. http://perl.plover.com/yak/lambda/ "How to write a 163 line
program to compute 1+1".

Ben
 

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

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top