开发者

How can I process a Perl array element in a shell script?

For example:

In Perl:

@array = (1,2,3);

system ("/tmp/a.sh @array" ); 

In my shell script, how do I handle this array in shell script? How do I handle the shell script to receive the arguments, and how do I use that array variable开发者_运维问答 in shell script?


This:

my @array = (1,2,3);   
system ("/tmp/a.sh @array" );

is equivalent to the shell command:

/tmp/a.sh 1 2 3

you can see this by simply printing out what you pass to system:

print "/tmp/a.sh @array";

a.sh should handle them like any other set of shell arguments.

To be safe, you should bypass the shell and pass the array in as arguments directly:

system "/tmp/a.sh", @array;

Doing this passes each element of @array in as a separate argument rather than as a space separated string. This is important if the values in @array contain spaces, for example:

my @array = ("Hello, world", "This is one argument");
system "./count_args.sh @array";
system "./count_args.sh", @array;

where count_args.sh is:

#!/bin/sh

echo "$# arguments"

you'll see that in the first one it gets 6 arguments and the second it gets 2.

A short tutorial on handling arguments in a shell program can be found here.

Anyhow, why write one program in Perl and one in shell? It increases complexity to use two languages and shell has no debugger. Write them both in Perl. Better yet, write it as a function in the Perl program.


The shell script receives its arguments in $@:

#!/bin/sh
# also works for Bash
for arg  # "in $@" is implied
do
    echo "$arg"
done

In Bash, they can also be accessed using array subscripts or slicing:

#!/bin/bash
echo "${@:2:1}"    # second argument
args=($@)
echo "${args[2]}"  # second argument
echo "${@: -1}"    # last argument
echo "${@:$#}"     # last argument


like this:

in Perl:

   @a=qw/aa bb cc/;
   system("a.sh ".join(' ',@a));

in shell (a.sh):

#!/bin/sh
i=1;
while test "$1"
do
    echo argument number $i = $1
    shift
    i=`expr $i + 1`
done


if you want to pass all array elements once:

my @array = qw(1 2 3);

system("/tmp/a.sh". join(" ", @array));

If you want to pass array elements one by one:

my @array = qw(1 2 3);
foreach my $arr (@array) {
     system("/tmp/a.sh $arr");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜