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)

Answers


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

Joining tables in sql server?

sql sql-server

In SQL Server, I am joining three tables like below.

OOP vs macro problem

c++ oop design

I came across this problem via a colleague today. He had a design for a front end system which goes like this:

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

perl hash loops key-value

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.