Perl - how do I get the previous key in a hash?

I have a hash that has been filled with an unknown number of keys that are strings. Each key's value is zero to start.

I want to iterate through this hash and for each element except the first, make its value equal the equivalent in another hash I have plus the previous value in this hash. So mathematically something like:

hash1:a = hash2:a;
hash1:b = hash2:b + hash1:a;
hash1:c = hash2:c + hash1:b;
hash1:d = hash2:d + hash1:c;
hash1:e = hash2:e + hash1:d;

I'm not even really sure I know how to do the first one as I don't know what the value or key is. I plan to sort it first, but as the keys could be any in a list I have I cannot specify what would be first exactly. I don't know how to reference the previous value based on the key. Is this possible?

(I don't have any code to show I'm afraid, I tried but I just realised that it is very wrong haha)


Hashes themselves are unordered, so they have no idea of a 'previous' key. You'd need to extract the keys using the keys function, sort them (as you said) and then refer to the previous element of the list of keys to find out what the previous key in your chosen order was.

Once you have that previous key, you can then access the value from the hash using the usual $hash{$key} syntax.

The trick then becomes accessing the previous key in the list, which probably entails iterating over the list by index, as a foreach loop doesn't give you any idea where in the list you currently are. Something like

for (my $i = 0; $i <= $#keys; ++$i) {
    if ($i == 0) { ... } # first key
    else { ... } # all other keys

might be appropriate.

Need Your Help

Sorted ArrayList not displaying?

java arrays list sorting

ArrayList &lt;String&gt; cdcollection = new ArrayList();

Convert Unix Timestamp to time zone?

php unix datetime timezone timestamp

I have a unix timestamp that is set to +5, but I'd like to convert it to -5, EST Standard time. I would just make the time stamp be generated in that time zone, but I'm grabbing it from another sou...