从Perl脚本中的数组设置外壳程序数组 [英] Set a shell array from an array in Perl script

查看:43
本文介绍了从Perl脚本中的数组设置外壳程序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Perl脚本:

I have the following Perl script:

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

我想通过bash脚本检索数组的值

I want to retrieve the values of the array via a bash script

#!/bin/bash
seq=$(perl vectTEST.pl)
# retrieve the column 1 of the Array     
echo $seq[0]

我的方法行不通.

推荐答案

您不能返回数组.这个概念没有意义,因为print产生字节流,而不是变量.

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.

例如,

$ 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.

另一种选择是打印出重新创建数组的外壳程序代码,并在外壳程序中eval打印该代码.

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

例如,

$ 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.

这篇关于从Perl脚本中的数组设置外壳程序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆