我有一个bash脚本,其中包含唯一的内容(数组),例如
locDbList=(default default_test)
我需要在Perl脚本中使用这个数组。
是否可以通过某种方式将数组定义从bash文件加载到Perl中?
如果没有,那么我如何定义具有相同数组的Perl文件并在第二个Perl脚本中加载?
在第二种情况下:
second_perl_file.sh ( load the perl_array in here ).
最后一个选项是将数组信息放入我可以从Perl和bash中读取的格式,例如ini文件
答案 0 :(得分:1)
如果在perl中运行%ENV
,则无法从declare -a
和事件中看到它,它仍然不会拉出直接外部作用域中定义的数组。
您可能必须为此工作两端。这并不容易,但这是一个开始。
首先,我创建了一个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_array
bash函数回显的内容。
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} );