Set a shell array from an array in Perl script

后端 未结 3 1806
旧巷少年郎
旧巷少年郎 2021-01-29 07:23

I have the following Perl script:

 sub {
    my $sequence=\"SEQUENCE1\";
    my $sequence2=\"SEQUENCE2\";
    my @Array = ($sequence, $sequence2);
    return \\@         


        
3条回答
  •  鱼传尺愫
    2021-01-29 07:45

    You can't return an array. The concept makes no sense since print produces a stream of bytes, not variables.


    One solution is to output a text representation of the array and have the shell parse it.

    For example,

    $ IFS=$'\n' array=( $(
       perl -e'
          my @array = ("a b", "c d", "e f");
          print "$_\n" for @array;
       '
    ) )
    
    $ echo ${#array[@]}
    3
    
    $ echo "${array[1]}"
    c d
    

    This particular implementation assumes your array can't contain newlines.


    The other alternative is to print out shell code that recreates the array and eval that code in the shell.

    For example,

    $ eval "array=( $(
       perl -e'
          use String::ShellQuote qw( shell_quote );
          my @array = ("a b", "c d", "e f");
          print join " ", map shell_quote($_), @array;
       '
    ) )"
    
    $ echo ${#array[@]}
    3
    
    $ echo "${array[1]}"
    c d
    

    This is a robust solution.

提交回复
热议问题