H.Epstein
H.Epstein

Reputation: 731

return array from perl to bash

I'm trying to get back an array from perl to bash.

My perl scrip has an array and then I use return(@arr)

from my bash script I use

VAR = `perl....

when I echo VAR I get the aray as 1 long string with all the array vars connected with no spaces.

Thanks

Upvotes: 1

Views: 668

Answers (2)

haukex
haukex

Reputation: 3013

In the shell (and in Perl), backticks (``) capture the output of a command. However, Perl's return is normally for returning variables from subroutines - it does not produce output, so you probably want print instead. Also, in bash, array variables are declared with parentheses. So this works for me:

$ ARRAY=(`perl -wMstrict -le 'my @array = qw/foo bar baz/; print "@array"'`); \
    echo "<${ARRAY[*]}> 0=${ARRAY[0]} 1=${ARRAY[1]} 2=${ARRAY[2]}"
<foo bar baz> 0=foo 1=bar 2=baz

In Perl, interpolating an array into a string (like "@array") will join the array with the special variable $" in between elements; that variable defaults to a single space. If you simply print @array, then the array elements will be joined by the variable $,, which is undef by default, meaning no space between the elements. This probably explains the behavior you mentioned ("the array vars connected with no spaces").

Note that the above will not work the way you expect if the elements of the array contain whitespace, because bash will split them into separate array elements. If your array does contain whitespace, then please provide an MCVE with sample data so we can perhaps make an alternative suggestion of how to return that back to bash. For example:

( # subshell so IFS is only affected locally
    IFS=$'\n'
    ARRAY=(`perl -wMstrict -e 'my @array = ("foo","bar","quz baz"); print join "\n", @array'`)
    echo "0=<${ARRAY[0]}> 1=<${ARRAY[1]}> 2=<${ARRAY[2]}>"
)

Outputs: 0=<foo> 1=<bar> 2=<quz baz>

Upvotes: 5

H&#229;kon H&#230;gland
H&#229;kon H&#230;gland

Reputation: 40778

Here is one way using Bash word splitting, it will split the string on white space into the new array array:

array_str=$(perl -E '@a = 1..5; say "@a"')
array=( $array_str )

for item in ${array[@]} ; do
    echo ": $item"
done

Output:

: 1
: 2
: 3
: 4
: 5

Upvotes: 1

Related Questions