perl - Modify key if it already exists -
i'm writing piece of code creates hoas , loops through each key. snippet below shows basic example of problem i'm having.
#!/usr/bin/perl use strict; use warnings; @array1 = qw (1 1 3 4 5); # note '1' appears twice @array2 = qw (a b c d e); @array3 = qw (6 7 8 9 10); @array4 = qw (f g h j); %hash; push @{$hash{$array1[$_]}}, [ $array2[$_], $array3[$_], $array4[$_] ] 0 .. $#array1; $key (sort keys %hash) { ($array2, $array3, $array4) = @{$hash{$key}[-1]}; print "[$key] $array2\t$array3\t$array4\n"; }
output:
[1] b 7 g [3] c 8 h [4] d 9 [5] e 10 j
for data i'm using (as opposed example) have been using key i've realised isn't unique, so, above end overriding non-uniqe keys. i'm using these values keys in order sort them later.
my question either:
a) can perform above task each key unless (exists $hash{$array1})
in case can modify it
or
b) there way sort values, in case use another, non-redundant key.
thanks!
so, above end overriding non-uniqe keys
you aren't. let's print out whole contents of hash:
for $key (sort { $a <=> $b } keys %hash) { # sort numerically! $array (@{ $hash{$key} }) { # loop on instead of $hash{$key}[-1] "[$key] " . join "\t", @$array; } }
output:
[1] 6 f [1] b 7 g [3] c 8 h [4] d 9 [5] e 10 j
you overriding values if building hash like
$hash{$array1[$_]} = [ $array2[$_], $array3[$_], $array4[$_] ] 0 .. $#array1;
(and printing as)
for $key ( ... ) { "[$key] " . join "\t", @{ $hash{$key} }; }
that is, assigning instead of push
ing.
if want keep first value assigned each key, use //=
operator (assign if undef
).
Comments
Post a Comment