【问题标题】:How to prevent duplicate element before pushing to an array in Perl如何在 Perl 中推送到数组之前防止重复元素
【发布时间】: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' =&gt; '11.0', 'Build' =&gt; '135' }, { 'Build' =&gt; '135', 'Release' =&gt; '11.0' }, { 'Release' =&gt; '12.0', 'Build' =&gt; '133' }, { 'Build' =&gt; '115', 'Release' =&gt; '11.0' } ];
  • 仅供参考,有重复的 { 'Release' =&gt; '11.0', 'Build' =&gt; '135' } ,所以我正在考虑删除第二个 { 'Release' =&gt; '11.0', 'Build' =&gt; '135' } 并保留第一个。
  • 您的代码有不平衡的大括号。这是一个完整的子程序吗?

标签: arrays perl hash


【解决方案1】:

所以我会为精简列表创建一个新数组,并创建一个哈希来跟踪您所看到的内容:

my ( @trimlist, %trimkeys ) ;
for ( @$json_releasebuild_array )
{
  my $kval= "r$_->{Release}b$_->{Build}" ;  # make a unique string for each entry
  next if exists $trimkeys{$kval} ;
  push @trimlist, $_ ;
  $trimkeys{$kval}= 1 ;
}

$json_releasebuild_array= \@trimlist ;

【讨论】:

    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 2021-01-19
    • 2020-10-04
    • 2020-04-16
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多