0

我有一个 bash 脚本,其中包含唯一的内容(一个数组),例如

bash_array.sh

locDbList=(default default_test)

我需要在 Perl 脚本中使用这个数组。

是否可以以某种方式将 bash 文件中的数组定义加载到 Perl 中?

如果不是,那么我如何定义具有相同数组的 Perl 文件并将其加载到第二个 Perl 脚本中?

在第二种情况下:

perl_array.pl

second_perl_file.sh ( load the perl_array in here ). 

最后一个选项是将数组信息以我可以从 Perl 和 bash 中读取的格式放置,例如 ini 文件

4

1 回答 1

1

如果您在 perl 中运行,您无法从%ENV事件中看到它declare -a,它仍然不会提取在直接外部范围中定义的数组。

为此,您可能必须在两端工作。这并不容易,但这是一个开始。

传递给 Perl

  • 首先,我创建了一个 bash 函数来准备传递这个值。

    function pass_array
    {
        # get the array name 
        declare array_name=$1;
        # get all declarations for defined arrays.
        # capture the line that corresponds with the array name
        declare declaration=$(declare -a | grep --perl-regex --ignore-case "\\b$array_name\\b");
        # - At this point this should look like:
        #   declare -a* array_name='([0]="value1", [1]="value2", [2]="value3")'
        # - Next, we strip away everything until the '=', leaving:
        #   '([0]="value1", [1]="value2", [2]="value3")'
        echo ${declaration#*=}; 
    }
    
  • 你可以像这样将它传递给 perl:

    perl -Mstrict -Mwarnings -M5.014 -MData::Dumper -e 'say Data::Dumper->Dump( [ \@ARGV ], [ q[*ARGV] ] )' "$(pass_array locDbList)"
    
  • 在 Perl 方面,您可能有一个这样的便利函数:

    sub array_from_bash {
        return shift =~ m/\[\d+\]="([^"]*)"/g;
    }
    

命名数组

当然,您可能希望保留数组的名称,以允许传递多个,或者动态定位它,例如使用其他环境变量。( export DB_LIST_NAME=locDBList)

在这种情况下,您可能想要更改pass_arraybash 函数的回声。

 echo echo ${declaration#*-a[b-z]* };

并且可能希望有这样的 Perl 函数:

sub named_array_from_bash {
    return unless my $array_name = ( shift // $_ );
    my $arr_ref = [ @_ ? @_ : @ARGV ];
    return unless @$arr_ref 
               or my ( $array_decl ) = 
                    grep { index( $_, "$array_name='(" ) == 0 } @$arr_ref
                    ;
    return array_from_bash( substr( $array_decl, length( $array_name ) + 1 ));
}

环境变量

然而,另一个想法是简单地导出具有相同信息的变量:

declare decl=$(declare -a | grep --perl-regex --ignore-case "\\b$array_name\\b");
export PERL_FROM_BASH_LIST1=${decl#*-a[a-z]* };

并从 Perl 中阅读。

my @array = array_from_bash( $ENV{PERL_FROM_BASH_LIST1} );
于 2013-01-17T18:18:24.817 回答