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

i have div and i want to set div height dependent on background-image height

javascript css

I have a dynamic JS code that changes the background image of div on each click. How can I change div height and width dependent on the image size?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.