I need to build a hash with unixtime keys and eliminate duplicates without losing entrieswhy do you need to remove duplicates in the first place? Is this so that you can use them as a hash key? One simple way to do that is to append a number in the key to make them unique:
You can still access the timestamp by splitting the keys.use Data::Dump qw(pp); my @array = qw<1000 1000 1000 1010 1010 1010 1020 1022 1023>; my %out; while (my ($pos, $val) = each @array) { $out{$val.':'.$pos} = { One => 1, Two => 1 }; } pp \%out; __END__ { "1000:0" => { One => 1, Two => 1 }, "1000:1" => { One => 1, Two => 1 }, "1000:2" => { One => 1, Two => 1 }, "1010:3" => { One => 1, Two => 1 }, "1010:4" => { One => 1, Two => 1 }, "1010:5" => { One => 1, Two => 1 }, "1020:6" => { One => 1, Two => 1 }, "1022:7" => { One => 1, Two => 1 }, "1023:8" => { One => 1, Two => 1 }, }
Here's another method, where you remove precision from the timestamp to replace it with an index (in my example below, with a precision of 10, I remove the last digit to replace it with a value between 0 and 9).
It won't work when there are too many timestamps that round down to the same value though (eg, if you remove the last two digits, you can't have 100 times the same value) and will change a value even if it was already new (1022 and 1023 became 1021 and 1022). On the other hand it's a single loop rather than two nested loops.my %out; my %index; my $precision = 10; for my $val (@array) { my $rounded = $precision*(int($val/$precision)); die "Too many duplicates" if exists $index{$rounded} and $index{$rou +nded} == $precision; my $timestamp = $rounded + $index{$rounded}++; $out{$timestamp} = { One => 1, Two => 1 }; } pp \%out; __END__ { 1000 => { One => 1, Two => 1 }, 1001 => { One => 1, Two => 1 }, 1002 => { One => 1, Two => 1 }, 1010 => { One => 1, Two => 1 }, 1011 => { One => 1, Two => 1 }, 1012 => { One => 1, Two => 1 }, 1020 => { One => 1, Two => 1 }, 1021 => { One => 1, Two => 1 }, 1022 => { One => 1, Two => 1 }, }
In reply to Re: goto HACK
by Eily
in thread goto HACK
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |