How do I remove duplicate characters and keep the unique one only in Perl?

前端 未结 11 762
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 16:08

How do I remove duplicate characters and keep the unique one only. For example, my input is:

EFUAHUU
UUUEUUUUH
UJUJHHACDEFUCU

Expected out

11条回答
  •  我在风中等你
    2020-12-05 16:31

    Tie::IxHash is a good module to store hash order (but may be slow, you will need to benchmark if speed is important). Example with tests:

    use Test::More 0.88;
    
    use Tie::IxHash;
    sub dedupe {
      my $str=shift;
      my $hash=Tie::IxHash->new(map { $_ => 1} split //,$str);
      return join('',$hash->Keys);
    }
    
    {
    my $str='EFUAHUU';
    is(dedupe($str),'EFUAH');
    }
    
    {
    my $str='EFUAHHUU';
    is(dedupe($str),'EFUAH');
    }
    
    {
    my $str='UJUJHHACDEFUCU';
    is(dedupe($str),'UJHACDEF');
    }
    
    done_testing();
    

提交回复
热议问题