我有一个代码块,我使用了很多次,但有一些细微的变化,我试图将其制作成子例程。
此代码块完成配置模板(路由器接口、VRF、其他网络内容)
它通过在哈希数据结构(称为 %config_hash)中查找数据来实现这一点,该数据结构是通过摄取 excel 文件构建的:P。查找的数据位于不同模板的哈希的不同区域中。
当前工作代码的示例如下:
my @temp_source_template = @{ clone ($source_template{$switch_int_template}) };
my %regex_replacements=(); ## hash for holding regex search and replace values, keys are !name! (look in template files) values taken from DCAP
my @regex_key =(); ## temp array used for whe more then one !name! on a line
my $find_string='';
foreach my $line (@temp_source_template){
my (@regex_key) = ( $line =~ /(\!.*?\!)/g ); ## match needs to be non greedy thus .*? not .*
foreach my $hash_refs (@regex_key){
my $lookup = $hash_refs =~ s/!//gri; ## remove ! from !name! so lookup can be done in DCAP file hash
my $excel_lookup = $lookup =~ s/_/ /gri;
$regex_replacements{$hash_refs} = $config_hash{'Vlan'}{$inner}{$excel_lookup}; ## lookup DCAP file hash a write value to regex hash
if (undef eq $regex_replacements{$hash_refs}){
$regex_replacements{$hash_refs} = $config_hash{'Switch'}{$outer}{$excel_lookup};
}
if (undef eq $regex_replacements{$hash_refs}){
$regex_replacements{$hash_refs} = $config_hash{'VRF'}{$middle}{$excel_lookup};
}
$find_string= $find_string . $hash_refs . '|' ;
}
}
因此,这将创建一个哈希 (regex_replacements),其中包含要查找的值(regex_replacements 中的哈希键)和要替换的值(regex_replacements 中的值)。它还构建一个在正则表达式中使用的字符串($find_string)。不同的模板将具有不同的哈希查找“路径”(例如 $config_hash{'Switch'}{$outer}{$excel_lookup} )或不同的顺序(实际上是最具体的匹配)
为了完整起见,这里是执行正则表达式替换的代码块:
foreach my $line (@temp_source_template){
my (@line_array) = split /(![A-Za-z_]*!)/, $line;
foreach my $chunk (@line_array){
my $temp_chunk = $chunk;
$chunk =~ s/($find_string)/$regex_replacements{$1}/gi;
if (!($chunk)){
$chunk = $temp_chunk;
}
}
$line = join ("", @line_array);
if ($line =~ /\!.*\!/){
print {$log} " ERROR line has unmatched variables deleting line \"$line\"\n";
$line ="";
}
}
所以我做了一些搜索,发现了这个:Perl:如何将数组转换为嵌套哈希键 https://stackoverflow.com/questions/11505100/perl-how-to-turn-array-into-nested-hash-keys这几乎正是我想要的,但我无法让它工作,因为我的变量引用是一个哈希,它的哈希变量引用只是“REF”,所以我在尝试使用哈希作为引用时遇到错误。
所以我不会发布我尝试过的内容,因为我并不真正理解该链接的魔力。
但我正在做的是将以下内容传递给子组件
my @temp_source_template = @{ clone ($source_template{$test}) };
my @search_array = ( ['VRF' ,$middle] , ['Switch' ,$outer]);
my $find_string, $completed_template = dynamic_regex_replace_fine_string_gen(\%source_config,\@temp_source_template, \@search_array);
我想返回 $find_string 和 regex_replacements 哈希引用。应该注意的是,在 sub 中,我需要将 $excel_lookup 的值附加到 @search 数组元素的末尾。
我不明白如何做的是构建变量级别哈希查找。