joe
joe

Reputation: 35097

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?

Upvotes: 2

Views: 2603

Answers (4)

Space
Space

Reputation: 7259

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");
}

Upvotes: -2

catwalk
catwalk

Reputation: 6476

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

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 360325

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

Upvotes: 2

Schwern
Schwern

Reputation: 165207

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.

Upvotes: 5

Related Questions