从字符串创建唯一值的数组的最佳方法是什么?

use*_*521 0 perl

Perl中是否有一个很好的衬里,可以让你从字符串中创建一个唯一值数组?

$str = "bob-2-4 asdfasdfasdf bob-2-4 asdfasdf bob-3-1";
my @unique = $str =~ m/(bob-\d-\d)/g;
# array is now "bob-2-4, bob-2-4, bob-3-1"
Run Code Online (Sandbox Code Playgroud)

我希望这个独特的阵列只包含"bob-2-4,bob-3-1".

ike*_*ami 5

没有模块:

sub uniq { my %seen; grep !$seen{$_}++, @_ }
Run Code Online (Sandbox Code Playgroud)

使用常用模块:

use List::MoreUtils qw( uniq );
Run Code Online (Sandbox Code Playgroud)

用法:

my $str = "bob-2-4 asdfasdfasdf bob-2-4 asdfasdf bob-3-1";
my @unique = uniq $str =~ m/(bob-\d-\d)/g;
say for @unique;
Run Code Online (Sandbox Code Playgroud)