Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello All, Trying to create a running total for by client using either a 2 dimensional array or hash. I'm basically reading through a file and get a value I want to have a running total for and each record has the name of the client, at the end I would like to print the whole array which results in each name and the total. I'm not sure first if an array or a hash is better and secondly based on what I have found online, I'm not seeing a good example to help me to understand how to accomplish this. A simple example would be a great starting point! Thanks!

Replies are listed 'Best First'.
Re: Running Total Array or Hash
by davido (Cardinal) on Mar 10, 2014 at 16:06 UTC

    We need more information. Please provide:

    • A few records worth of sample input.
    • 5-25 lines of code that you already have, that compiles, and that demonstrates as concisely as practical what you need help with.
    • Sample output that you want to be produced given the sample input you demonstrated.

    Dave

Re: Running Total Array or Hash
by kennethk (Abbot) on Mar 10, 2014 at 16:52 UTC
    As others have pointed out, you are light on specifics. The more specific you are, the more helpful we can be. This includes sample input, scrubbed as necessary and wrapped in code tags; desired output, wrapped in code tags; and attempted code or at least a description of your algorithm. See How do I post a question effectively?.
    each record has the name of the client
    This sounds like indexing results by strings, which says "use a hash" to me. Algorithmically, that might look something like:
    #!/usr/bin/perl -w use strict; my %sum; while (<DATA>) { my ($name, $value) = split; $sum{$name} += $value; } for my $key (sort keys %sum) { print "$key: $sum{$key}\n"; } __DATA__ a 1 b 5 a 3 b 7 c 9 a 2

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      Hello All, Thank you KennethK, This is exactly what I needed, just enough to give me direction. Worked like a charm!
        Hello, I guess I have 1 additional component. Assuming I display everything properly can I manipulate the total with a math formula and put it back in the array prior to printing it?
        for my $key (sort keys %client_total) { $client_total = {$key} = $client_total/10; } for my $key (sort keys %client_total) { print "$key: $client_total{$key}\n"; }
        I'm not clear on on how to manipulate the value, the above gives me an error. Thanks!!
Re: Running Total Array or Hash
by toolic (Bishop) on Mar 10, 2014 at 16:04 UTC
    Without seeing your input file or the output you desire, it is hard to give a code example. However, I think a hash might be preferable to an array due to potentially easier access. perlintro