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

I have a hashref, @records ($records->{name} would hold the value xxx or yyy), and it contains the following values:
name | passed | failed | pending ------+--------+--------+--------- xxx | null | 2 | null xxx | 30 | null | null xxx | null | null | 10 yyy| 6 | null | null
How do you process @records, and make it like this:
name | passed | failed | pending ------+--------+--------+--------- xxx | 30 | 2 | 10 yyy| 6 | null | null
What I want is clean up 3 lines of xxx's into 1 line.

Replies are listed 'Best First'.
Re: cleaning up multiple lines...
by Not_a_Number (Prior) on Mar 23, 2004 at 21:45 UTC

    Not sure what you mean by:

    I have a hashref, @records...

    I thought (more knowlegeable monks will no doubt correct me if I'm wrong) that hashrefs were scalars, not arrays.

    Anyway, if perchance you mean that you have this data in a file somewhere, you could do something like this (note that, to simplify, I use __DATA__ instead of opening the file and reading from the filehandle):

    use strict; use warnings; my $headline = <DATA>; my %HoA; while ( <DATA> ) { s/null/0/g; # no warnings 'numeric'; next unless /^\w/; chomp; my ( $name, @res ) = split /\s*\|\s*/; $HoA{$name} = ! $HoA{$name} ? [ @res ] : [ map { $HoA{$name}[$_] + $res[$_] } 0 .. $#res ]; } print $headline; { local $" = ' | '; print "$_: @{ $HoA{$_} }\n" for ( keys %HoA ); } __DATA__ name | passed | failed | pending -----+--------+--------+--------- xxx | null | 2 | null xxx | 30 | null | null xxx | null | null | 10 yyy| 6 | null | null

    The first line in the while() loop changes all your instances of 'null' to '0'. If you really don't want to do this, the easiest solution is probably to remove that line and uncomment the following line. There are other solutions, but I haven't really the time to find any that don't complicate the code significantly (hey, anyone else out there?...)

    hth

    dave

Re: cleaning up multiple lines...
by Anonymous Monk on Mar 23, 2004 at 22:10 UTC
    Hi Dave, Sorry I wasn't clear in my post. The piece of data below is from the sql. It's not a text datafile. So your solution doesn't work. This is the piece of code I used to retrieve data from the database and save the output into @records.
    while ( $rec = $sth->fetchrow_hashref() ) { push @records, $rec; } @records now contains: name | passed | failed | pending ------+--------+--------+--------- xxx | null | 2 | null xxx | 30 | null | null xxx | null | null | 10 yyy| 6 | null | null