in reply to Updating arrays within hashes

jonnyw83:

You're already working with people on some answers, so this post is just a couple observations about your code.

First, I'm wondering if using a pair of hashes with identical keys is a good idea. It can be, but I can't tell without knowing more about your program. I tend to use a single hash, and add a level to handle the split. For example, if you're comparing the contents of a pair of files, rather than having a hash for each file, you could add keys (such as FILE1 and FILE2) for the different files after your primary key:

for my $key (keys %hash) { if (exists $hash{$key}{FILE1}) { if (exists $hash{$key}{FILE2}) { # Key exists in both files } else { # Key exists only in file 1 } } else { # Key exists only in file 2 } }

Second: if you choose a different indentation style, you wouldn't need the comments that tell you '#closes if loop' -- good use of whitespace can make it obvious. There are quite a few different indentation styles that can make it clear. For example, you can vertically align the closing curly brace with the structure that's being closed:

foreach my $key (keys (%hasha)) { if (my @temp = grep( /$key/, @prevarray ) ) { push(@{$hasha{$key}},$value); next; } else { push (@{$hashb{$key}},$value); next; } }

Another popular method is to vertically align the open and closing curly braces, either indented:

foreach my $key (keys (%hasha)) { if (my @temp = grep( /$key/, @prevarray ) ) { push(@{$hasha{$key}},$value); next; } else { push (@{$hashb{$key}},$value); next; } }

or not:

foreach my $key (keys (%hasha)) { if (my @temp = grep( /$key/, @prevarray ) ) { push(@{$hasha{$key}},$value); next; } else { push (@{$hashb{$key}},$value); next; } }

There are many variations, and plenty of religious wars over indentation style. Don't get caught up in the wars, just be consistent within each script. Most people can easily get used to any of the styles fairly quickly, so don't get too hung up on it.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Updating arrays within hashes
by jonnyw83 (Initiate) on Feb 10, 2011 at 16:40 UTC
    Hi. I usually do keep everthing aligned in my editor for some reason it kept misaligning when copy and pasting it in to the web browser, hence I added the comments for clarity. Probably should have just re-aligned them.... Thanks for the tip on the different keys within a single array i hadn't thought of that. May actually be easier to restructure my programme that way. Although how to add elements to an array hash based on the outcome of a logical statement is still something I'll want to do. I've looked at some of the PERL documentation and couldn't find and examples of this to clarify. There's plenty on data structure but I couldn't find much on altering arrays within hashes to clarify why this is going wrong. Will attempt to sort it and post again if still struggling.