Imran Imran - 4 months ago 9
Perl Question

Accessing Perl array in bash

I have a perl code where I execute some bash commands using backticks. I want to read a perl array in that bash command. My array has some strings and I want to read them in a for loop of bash.

my @aArray = (1,2,3,4);
my $command = 'for i in $@aArray; do xxxxx $i; done;';
`$command`


I also want to catch error if any part of the loop fails. Thanks

Answer

As @chepner has suggested, the code you want looks a bit like this:

my @array = (1, 2, 3, 4);
for my $val (@array) {
    # Pick your favourite/the most appropriate mechanism for making system calls
    system("command", $val);
}

If you need to make a single call on a remote system, what you could do is something like this:

my @array = (1, 2, 3, 4);
my $command = "for i in ("

for my $val(@array) {
    $val =~ s/(?<!\\) /\\ /g; # Escape spaces that haven't already been (if the array elements might contain them)
    $command = "$command $val";
}

$command = $command."); do <command> $i; done;";

system($command);