in reply to Hash/Array help

Welcome to the Perl community. You might find it helpful to read How do I post a question effectively? to learn a bit more about formatting in the Monastery and what we like to see in a question.

If you work with Perl for any significant amount of time, you'll find that the hash is frequently the easiest way to do things, and I think once you get comfortable using them your facility with the language will increase dramatically.

In this case, I would suggest using a hash of lists in order to hold your data - a basic intro to nested structures in Perl can be found at perllol. You'll probably also want to read up on references at perlref and perlreftut. Since you are using CSV files, it's also probably a good idea to use Text::CSV to handle your files, to avoid unnecessary headaches. Obviously I have no idea if you are already or not, since you haven't posted any code - that's something we usually like to see.

To give you a basic idea of how to use a hash of lists, I've put together the following code with your example:

#!/usr/bin/perl use strict; use warnings; my %servers; while (<DATA>) { chomp; my @line = split /\,/; my $name = shift @line; if (exists $servers{$name}) { foreach my $index (0..$#line) { $servers{$name}[$index] += $line[$index]; } } else { $servers{$name} = [@line]; } } foreach my $key (keys %servers) { print join(',',$key,@{$servers{$key}}), "\n"; } __DATA__ server1,4,2,2 server1,6,2,2 server1,4,1,1 server2,10,1,2 server2,1,1,1

Replies are listed 'Best First'.
Re^2: Hash/Array help
by ikegami (Patriarch) on Jul 30, 2009 at 16:18 UTC
    I notice you're always escaping characters that don't need escaping in regex patterns. It's harder to read.
      When I first starting learning regexes, one of the books I was reading suggested doing that as future proofing - just because a punctuation character has no meaning in a regular expression now does not mean it won't in the future, and that would be a bug I'd hate to try and track down. I do agree that the result is my expressions suffer from leaning_toothpick_syndrome. I've cut back a bit, but something about that darned comma just begs to be escaped.
        I wouldn't fret it. They're careful with their additions.
        • ?/*/+/{} followed by ?
        • ?/*/+/{} followed by +
        • \ followed by new letters
        • ( followed by ?
        • ( followed by *
        • (? followed by new characters

        In every case, they used sequences that were previously illegal.