perl脚本中的Bash数组
我有一个bash脚本,它只包含内容(一个数组),例如 bash_arrray.sh 我需要在Perl脚本中使用这个数组 是否可以以某种方式将数组定义从bash文件加载到Perl中 如果不是,那么我如何用相同的数组定义一个Perl文件并将其加载到第二个Perl脚本中 在第二种情况下: perl_arrray.plperl脚本中的Bash数组,perl,bash,ini,Perl,Bash,Ini,我有一个bash脚本,它只包含内容(一个数组),例如 bash_arrray.sh 我需要在Perl脚本中使用这个数组 是否可以以某种方式将数组定义从bash文件加载到Perl中 如果不是,那么我如何用相同的数组定义一个Perl文件并将其加载到第二个Perl脚本中 在第二种情况下: perl_arrray.pl 最后一个选项是以我可以从Perl和bash中读取的格式放置数组信息,例如ini文件,从%ENV中看不到它,如果在Perl中运行declare-a,它仍然不会提取在直接外部作用域中定义的数
最后一个选项是以我可以从Perl和bash中读取的格式放置数组信息,例如ini文件,从
%ENV
中看不到它,如果在Perl中运行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; }
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 )); }
export DB\u LIST\u NAME=locDBList
)
在这种情况下,您可能需要更改pass\u数组
bash函数的回声
echo echo ${declaration#*-a[b-z]* };
可能需要一个Perl函数,如下所示:
sub array_from_bash {
return shift =~ m/\[\d+\]="([^"]*)"/g;
}
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} );
我有一种感觉,你有一个。为什么需要两个Perl脚本?你到底想干什么?为什么不能在一个Perl脚本中编写所有代码?一个Bash脚本?我有一个Bash脚本,它构建一个包,并将Bash中的用户参数以数组的形式放入文件中。稍后在包安装过程中(基于perl)。我想在perl中使用这些值,thanks@JonathanLeffler您建议如何存储可从perl和bash轻松访问的配置数据, thanks@sakhunzai,您可以显示bash文件的一些示例内容吗?@dan1111bash有一个简单的数组:
locDbList=(默认\u测试)