考慮這個陣列:
my @array = (hashref1, hashref2, hashref3, hashref1);
如何洗掉重復的參考hashref1
。
uj5u.com熱心網友回復:
如果“重復參考”是指它們都參考相同的匿名哈希,則可以使用List::Util的uniq
:
#!/usr/bin/perl
use warnings;
use strict;
use List::Util qw{ uniq };
use Data::Dumper;
my $hashref1 = {a => 10};
my $hashref2 = {b => 11};
my $hashref3 = {c => 12};
my @array = ($hashref1, $hashref2, $hashref3, $hashref1);
print Dumper(uniq(@array));
輸出:
$VAR1 = {
'a' => 10
};
$VAR2 = {
'b' => 11
};
$VAR3 = {
'c' => 12
};
參考的字串化版本將用于比較,例如HASH(0x560ee5fdf220)
. 相同的參考具有相同的地址。
但是,如果您的意思是它們參考具有相同內容的不同物件,您需要找到一種方法如何對 hashrefs 進行字串化,以使內容始終相同。
#!/usr/bin/perl
use warnings;
use strict;
use List::Util qw{ uniq };
use Data::Dumper;
my $hashref1 = {a => 10, A => 2};
my $hashref2 = {b => 11, B => 3};
my $hashref3 = {c => 12, C => 4};
my $hashref4 = {a => 10, A => 2};
my @array = ($hashref1, $hashref2, $hashref3, $hashref4);
my @serialized = do {
# Comment out the following line to see how 1 and 4
# can be different sometimes.
local $Data::Dumper::Sortkeys = 1;
map Dumper($_), @array;
};
my $VAR1;
print Dumper(map eval, uniq(@serialized));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516897.html
標籤:perl
下一篇:Perl搜索字串并列印出一行