如何在没有任何重复的情况下合并两个数组

时间:2010-07-15 13:41:32

标签: perl

@tools = ("hammer", "chisel", "screwdriver", "boltcutter",
           "tape", "punch", "pliers"); 
@fretools =("hammer", "chisel", "screwdriver" ,"blade");

push @tools,@fretools if grep @tools,@fretools

我得到了工具

  @tools=("hammer", "chisel", "screwdriver", "boltcutter", 
       "tape", "punch", "pliers", "blade");

有什么简单的方法吗?

3 个答案:

答案 0 :(得分:9)

List::MoreUtils CPAN模块具有uniq功能来执行此操作。如果您不想依赖此模块进行安装,只需从模块的源代码中复制uniq函数(因为它是纯Perl)并将其直接粘贴到您自己的代码中(具有适当的确认) 。一般而言,使用CPAN代码的优势在于其行为已记录在案并且经过充分测试。

use strict;
use warnings;
use Data::Dumper;

sub uniq (@) {
    # From CPAN List::MoreUtils, version 0.22
    my %h;
    map { $h{$_}++ == 0 ? $_ : () } @_;
}

my @tools = ("hammer", "chisel", "screwdriver", "boltcutter",
             "tape", "punch", "pliers"); 
my @fretools =("hammer", "chisel", "screwdriver" ,"blade");
@tools = uniq(@tools, @fretools);
print Dumper(\@tools);

__END__

$VAR1 = [
          'hammer',
          'chisel',
          'screwdriver',
          'boltcutter',
          'tape',
          'punch',
          'pliers',
          'blade'
        ];

答案 1 :(得分:4)

肯定有一个模块可以为你做这件事但没有模块:

my %uniques;
@uniques{@tools} = @tools x (1);
@uniques{@fretools} = @fretools x (1);
@tools = sort keys %uniques;

这使工具的顺序不同。如果您想保留订单,则需要采用不同的方法。

my %uniques;
@uniques{@tools} = @tools x (1);
for (@fretools) {
    push @tools, $_ if ! $uniques{$_};
}

答案 2 :(得分:1)

您可以尝试使用哈希,然后提取密钥以获取唯一元素:

use strict; 

my @tools = ("hammer", "chisel", "screwdriver", "boltcutter", "tape", "punch", "pliers");  
my @fretools =("hammer", "chisel", "screwdriver" ,"blade"); 

push @tools,@fretools if grep @tools,@fretools;

my %hash   = map { $_, 1 } @tools;
my @array = keys %hash;

print "@array";