【发布时间】:2013-12-23 07:15:02
【问题描述】:
请问在追加到数组之前如何做验证(停止追加重复元素)?
sub create_release_text_file {
my $result_path = shift;
my %hshReleasebuild;
my $json_releasebuild_array;
my $json_releasebuild_text;
my $json = JSON->new->allow_nonref;
$hshReleasebuild{"Build"} = $ARG_BUILD;
$hshReleasebuild{"Release"} = $ARG_RELEASE;
my $release_path = File::Spec->catfile($result_path, "release.txt");
if (-e $release_path) {
open RELEASE_FILE, "<", $release_path or die $!;
my $json = do { local $/; <RELEASE_FILE> };
$json_releasebuild_array = decode_json($json);
close RELEASE_FILE;
# print Dumper(\$json_releasebuild_array);
}
# Do the validation here before appending into the array
push(@{$json_releasebuild_array}, \%hshReleasebuild);
$json_releasebuild_text = $json->encode(\@{$json_releasebuild_array});
open RELEASE_FILE, ">", $release_path or die $!;
print RELEASE_FILE $json_releasebuild_text;
close RELEASE_FILE;
【问题讨论】:
-
什么标准确定是否出现重复,
$json_releasebuild_array中的数据是什么样的?通常,检查重复的最佳方法是将项目存储在散列中,其中散列键是确定重复的基本要素,值是完整的数据项。 Perl FAQ 中有各种关于此类主题的问题。 -
$json_releasebuild_array 看起来像:
[ { 'Release' => '11.0', 'Build' => '135' }, { 'Build' => '135', 'Release' => '11.0' }, { 'Release' => '12.0', 'Build' => '133' }, { 'Build' => '115', 'Release' => '11.0' } ]; -
仅供参考,有重复的
{ 'Release' => '11.0', 'Build' => '135' },所以我正在考虑删除第二个{ 'Release' => '11.0', 'Build' => '135' }并保留第一个。 -
您的代码有不平衡的大括号。这是一个完整的子程序吗?