如何打印 Perl 数组中的唯一元素?

发布于 2024-07-11 21:49:08 字数 324 浏览 5 评论 0原文

我在 while 语句期间将元素推入数组。 每个元素都是老师的名字。 当循环结束时,数组中最终会出现重复的教师姓名。 有时它们在阵列中并不紧邻,有时则紧邻。

在完成将值推入其中后,如何仅打印该数组中的唯一值? 每次我想打印一个元素时,不必解析整个数组。

将所有内容推入数组后的代码如下:

$faculty_len = @faculty;
$i=0;
while ($i != $faculty_len)
{
        printf $fh '"'.$faculty[$i].'"';
        $i++;
}   

I'm pushing elements into an array during a while statement. Each element is a teacher's name. There ends up being duplicate teacher names in the array when the loop finishes. Sometimes they are not right next to each other in the array, sometimes they are.

How can I print only the unique values in that array after its finished getting values pushed into it? Without having to parse the entire array each time I want to print an element.

Heres the code after everything has been pushed into the array:

$faculty_len = @faculty;
$i=0;
while ($i != $faculty_len)
{
        printf $fh '"'.$faculty[$i].'"';
        $i++;
}   

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

2024-07-18 21:49:08
use List::MoreUtils qw/ uniq /;
my @unique = uniq @faculty;
foreach ( @unique ) {
    print $_, "\n";
}
use List::MoreUtils qw/ uniq /;
my @unique = uniq @faculty;
foreach ( @unique ) {
    print $_, "\n";
}
深巷少女 2024-07-18 21:49:08

最好的选择是使用(基本上)内置工具,例如 uniq(如 innaM 所描述)

如果您没有能力使用 uniq 并且想要保留顺序,您可以使用 grep 来模拟它。

my %seen;
my @unique = grep { ! $seen{$_}++ } @faculty;
# printing, etc.

这首先为您提供一个散列,其中每个键都是每个条目。 然后,迭代每个元素,计算它们的数量,并添加第一个元素。 (更新了 brian d foy 的评论)

Your best bet would be to use a (basically) built-in tool, like uniq (as described by innaM).

If you don't have the ability to use uniq and want to preserve order, you can use grep to simulate that.

my %seen;
my @unique = grep { ! $seen{$_}++ } @faculty;
# printing, etc.

This first gives you a hash where each key is each entry. Then, you iterate over each element, counting how many of them there are, and adding the first one. (Updated with comments by brian d foy)

若有似无的小暗淡 2024-07-18 21:49:08

我建议将其放入哈希中。
像这样:

my %faculty_hash = ();
foreach my $facs (@faculty) {
  $faculty_hash{$facs} = 1;
}
my @faculty_unique = keys(%faculty_hash);

I suggest pushing it into a hash.
like this:

my %faculty_hash = ();
foreach my $facs (@faculty) {
  $faculty_hash{$facs} = 1;
}
my @faculty_unique = keys(%faculty_hash);
多像笑话 2024-07-18 21:49:08
@array1 = ("abc", "def", "abc", "def", "abc", "def", "abc", "def", "xyz");

@array1 = grep { ! $seen{ $_ }++ } @array1;

print "@array1\n"; 
@array1 = ("abc", "def", "abc", "def", "abc", "def", "abc", "def", "xyz");

@array1 = grep { ! $seen{ $_ }++ } @array1;

print "@array1\n"; 
云仙小弟 2024-07-18 21:49:08

perldoc 中有多种解决方案回答了这个问题。 只需在命令行输入:

perldoc -q duplicate

This question is answered with multiple solutions in perldoc. Just type at command line:

perldoc -q duplicate
很糊涂小朋友 2024-07-18 21:49:08

请注意:某些包含哈希的答案将更改数组的顺序。 哈希没有任何顺序,因此获取键或值将生成一个具有未定义顺序的列表。

这不适用于 grep { ! $seen{$_}++ } @faculty

Please note: Some of the answers containing a hash will change the ordering of the array. Hashes dont have any kind of order, so getting the keys or values will make a list with an undefined ordering.

This doen't apply to grep { ! $seen{$_}++ } @faculty

是你 2024-07-18 21:49:08

这是一个单行命令,用于按其出现的顺序打印唯一的行。

perl -ne '$seen{$_}++ || print $_' fileWithDuplicateValues

This is a one liner command to print unique lines in order it appears.

perl -ne '$seen{$_}++ || print $_' fileWithDuplicateValues
何止钟意 2024-07-18 21:49:08

我刚刚找到了陈腐的 3 班轮,享受吧

my %uniq; 
undef @uniq(@non_uniq_array); 
my @uniq_array = keys %uniq; 

I just found hackneyed 3 liner, enjoy

my %uniq; 
undef @uniq(@non_uniq_array); 
my @uniq_array = keys %uniq; 
海拔太高太耀眼 2024-07-18 21:49:08

这是另一种方法,仅当您不关心顺序时有用:

my %hash;
@hash{@faculty}=1;
my @unique=keys %hash;

如果您想避免声明新变量,则可以使用某种未充分记录的全局变量 %_

@_{@faculty}=1;
my @unique=keys %_;

Just another way to do it, useful only if you don't care about order:

my %hash;
@hash{@faculty}=1;
my @unique=keys %hash;

If you want to avoid declaring a new variable, you can use the somehow underdocumented global variable %_

@_{@faculty}=1;
my @unique=keys %_;
迟到的我 2024-07-18 21:49:08

如果您需要以任何方式处理教师列表,则将数组上的映射转换为用于键合并的哈希值,然后对键进行排序是另一种好方法:

my @deduped = sort keys %{{ map { /.*/? ($_,1):() } @faculty }};
print join("\n", @deduped)."\n";

通过更改 /.*/ 正则表达式用于相应地选择或解析和捕获,并且您可以通过使 ($_,1):() 任意复杂来每次传递输出一个或多个变异的、非唯一的键。

如果您需要使用替换正则表达式修改正在运行的数据,例如从名称中删除点 (s/\.//g),那么根据上述模式的替换将改变由于 $_ 别名而导致的原始 @faculty 数组。 您可以通过制作 @faculty 数组的匿名副本来绕过 $_ 别名(请参阅所谓的 "baby cart" 运算符):

my @deduped = sort keys %{{ map {/.*/? do{s/\.//g; ($_,1)}:()} @{[ @faculty ]} }};
print join("\n", @deduped)."\n";
print "Unmolested array:\n".join("\n", @faculty)."\n";

在最新版本的 Perl 中,您可以传递 key hashref,您可以使用非破坏性替换:

my @deduped = sort keys { map { /.*/? (s/\.//gr,1):() } @faculty };

否则,其他地方的 grep$seen[$_]++ 解决方案可能更好。

If you need to process the faculty list in any way, a map over the array converted to a hash for key coalescing and then sorting keys is another good way:

my @deduped = sort keys %{{ map { /.*/? ($_,1):() } @faculty }};
print join("\n", @deduped)."\n";

You process the list by changing the /.*/ regex for selecting or parsing and capturing accordingly, and you can output one or more mutated, non-unique keys per pass by making ($_,1):() arbitrarily complex.

If you need to modify the data in-flight with a substitution regex, say to remove dots from the names (s/\.//g), then a substitution according to the above pattern will mutate the original @faculty array due to $_ aliasing. You can get around $_ aliasing by making an anonymous copy of the @faculty array (see the so-called "baby cart" operator):

my @deduped = sort keys %{{ map {/.*/? do{s/\.//g; ($_,1)}:()} @{[ @faculty ]} }};
print join("\n", @deduped)."\n";
print "Unmolested array:\n".join("\n", @faculty)."\n";

In more recent versions of Perl, you can pass keys a hashref, and you can use the non-destructive substitution:

my @deduped = sort keys { map { /.*/? (s/\.//gr,1):() } @faculty };

Otherwise, the grep or $seen[$_]++ solutions elsewhere may be preferable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文