我无法从数组中删除重复项,只能获取数组的最后一个元素
我知道有一个类似的问题,但我从那里获取了提示并应用于我的代码以删除重复项。我得到的只是数组的最后一个元素。我看不出我哪里出了问题。请帮我找出我哪里出错了。
use strict;
use warnings;
use File::Find;
use Data::Dumper;
use List::MoreUtils qw/ uniq /;
my $localdir = 'images/p/';
my @filefound;
my @split1;
my $before;
find(sub {push @filefound, $File::Find::name if /.jpg$/ },$localdir);
for(@filefound) { print "$_ \n";}
foreach (@filefound){
my @result = split('_',$_);
@split1 = $result[0];
}
my %unique = ();
foreach my $item (@split1)
{
$unique{$item} ++;
}
my @myuniquearray = keys %unique;
foreach (@myuniquearray){ print "$_ \n";}
I know there is a similar question but I took tips from there and applied to my code to remove the duplicates. All I am getting is just the last element of the array. I am unable to see where I am going wrong. please help me find out where a I am going wrong.
use strict;
use warnings;
use File::Find;
use Data::Dumper;
use List::MoreUtils qw/ uniq /;
my $localdir = 'images/p/';
my @filefound;
my @split1;
my $before;
find(sub {push @filefound, $File::Find::name if /.jpg$/ },$localdir);
for(@filefound) { print "$_ \n";}
foreach (@filefound){
my @result = split('_',$_);
@split1 = $result[0];
}
my %unique = ();
foreach my $item (@split1)
{
$unique{$item} ++;
}
my @myuniquearray = keys %unique;
foreach (@myuniquearray){ print "$_ \n";}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题出在这里:
您每次通过循环都重新分配
@split1
。尝试push @split1, $result[0];
将新元素推送到现有列表中。The problem lies here:
You are reassigning
@split1
each time through the loop. Trypush @split1, $result[0];
instead to push the new element onto the existing list.在第一个 foreach 中,您在每次迭代中覆盖
@split1
而不是将结果添加到列表中。In the first foreach you are overwriting
@split1
in every iteration instead of adding the result to a list.