tags:

views:

189

answers:

2

I'm working on a Perl script that I was hoping to capture a string entered on the command line without having to enter the quotes (similiar to bash's "$@" ability). I'll be using this command quite a bit so I was hoping that this is possible. If I have:

if ($ARGV) {

I have to put the command line string in quotes. I'd rather do the command something like this:

htmlencode some & HTML <> entities

Without the quotes. Is there a way to do this in Perl?

+4  A: 

The @ARGV array contains the arguments to the Perl script - no quotes needed.

That said, the question asks about:

I have to put the command line string in quotes. I'd rather do the command something like this:

 htmlencode some & HTML <> entities

Without the quotes. Is there a way to do this in perl?

Well, if the command shown is written at the shell command line, you have to obey shell conventions - which means escaping the '&' and '<>' to prevent the shell from interpreting them. Likewise, within a Perl script, that sequence would need to be protected from Perl. Maybe you'd write:

system "htmlencode", "some", "&", "HTML", "<>", "entities";

That is, everything would have to be in quotes - but that notation would avoid executing the shell and having the shell interpret the commands.

Alternatively again, if you put the arguments into an array (with quotes at the time the array is loaded), then you could pass that array to system and not use any quotes:

my @args = ( "htmlencode", "some", "&", "HTML", "<>", "entities" );
system @args;

But I think the question is confused.

Jonathan Leffler
+3  A: 

You put quotes around $@ in bash so that it expands to have each element in the array quoted. The reason to do that is so that each element of the array continues to be treated as a single argument when you pass them all to the next command.

The analogue to that in Perl is when you want to pass those parameters to another external command. If you're running the external program with the backtick operators, then you'd need to quote each parameter, but if you use system, then Perl will take care of keeping all the parameters separate for you.

In fact, separate parameters are the way programs are executed on Unix anyway. The single-string command-line format is there because we need to be able to type things at the command prompt. Like all shells, bash has special rules about how to split that single string into multiple arguments. But if you already have them separated in a Perl array, don't put them back into a single string. Keep them separate.

Rob Kennedy