user1887163
user1887163

Reputation: 23

Passing variable number of arguments to function in a perl script

I am working with a perl program that is going to have a variable number of arguments/parameters. Basically, my perl program is run by doing something along the lines of:

perl progam.pl hello, I am a simple statement

The program does some odds and ends, but that's not important to what I'm trying to ask here. What I want to do with the "hello, I am a simple statement" part is pass that to the echo function within the perl script.

Though it should work with any number of arguments/parameters.

Any ideas? Thank you!

Upvotes: 1

Views: 1646

Answers (1)

ikegami
ikegami

Reputation: 385645

When you execute the shell command

perl progam.pl hello, I am a simple statement

It launches perl and passes these 7 arguments to it:

  • progam.pl
  • hello,
  • I
  • am
  • a
  • simple
  • statement

perl, in turn, will execute progam.pl after populating @ARGV with the other arguments. As such, you could do

system("echo", join(" ", @ARGV));

Or course, that's exactly what echo does, so you could simply do

system("echo", @ARGV);

Or did you mean print when you said echo (cause it doesn't make much sense to execute echo)?

print(join(" ", @ARGV), "\n");

Note that it would be better if you passed the text as a single argument.

perl progam.pl 'hello, I am a simple statement'

Your approach will fail, for example, if some of the words had more than one space between them.

Upvotes: 6

Related Questions