简体   繁体   English

从数组中删除原始元素而不删除其在 perl 中的重复项

[英]remove original element from an array without removing its duplicates in perl

I have an array with duplicate elements.我有一个包含重复元素的数组。 I would like to remove one element at a time without iterating in a loop.我想一次删除一个元素而不在循环中迭代。 Also, if I remove an element, if any duplicate element exists for that element it should remain in the array.此外,如果我删除一个元素,如果该元素存在任何重复元素,它应该保留在数组中。 Is there any way to do this in perl?有没有办法在 perl 中做到这一点?

One loop to store elements in hash, and one grep to show remaining elements.一个循环将元素存储在哈希中,一个 grep 显示剩余元素。 All this assuming that undef is not occurring as value in your array of duplicates.所有这些都假设undef没有作为重复数组中的值出现。

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

my @r = (1..8, 1..8);

my %ref;
push @{ $ref{$_} }, \$_ for @r;

my $to_remove = 2;
undef ${shift @{ $ref{$to_remove} }};
print Dumper \@r;

undef ${shift @{ $ref{$to_remove} }};
print Dumper \@r;

print Dumper [ grep defined, @r ];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM