combining nested data structure into one array

I have a subroutine that returns 3 array refs. so i have:
my ($stats, $totals, $loads) = gets_stats();
$stats and $totals are reference to arrays of arrays. $loads is just a ref to an array. what i want to do is is combine each "record" of each array into one. here is how the structure look:
$stats -> @array -> [user, cpu, mem]
$totals -> @array -> [tot_cpu, tot_mem]
$loads -> [load1, load2]

so i would like to itereate thru each of these array and end up with
@stats = [ user, cpu, mem, tot_cpu, tot_mem, load1, load2]
         [ ..another record...]
         [ ..another record...] ...etc....

any ideas? please let me know if you need further explanation of this question. thanks

Who is Participating?

Improve company productivity with a Business Account.Sign Up

skolupaevConnect With a Mentor Commented:
Hi jkip66,

This is pretty easy if you are certain the arrays
@$stats and @$totals have the same size.   I'd do something like what follows, assuming there is no need to
check on them.    

The main trick to this is getting at the value of an anonymous array, for example $a.  

When $a = [ 'x', 'y', 'z' ], @{$a} gathers all the values in $a and returns a list value ( 'x', 'y', 'z' ).   @$a is a shorthand for @{$a}.

In an array context, @$a returns the list of values.
In a scalar context it returns the number of values in the list.

######### a solution to try ############

@stats=();             # put result here
($stats, $totals, $loads) = &gets_stats();

for ($ix=0; $ix < @$stats; $ix++)

   $stats3 = $stats->[$ix];     # get [usr,cpu,mem]
   $totals2 = $totals->[$ix];   # get [totcpu, totmem]
   push( @stats,  [ @$stats3, @$totals2, @$loads ]  )
   # each iteration pushes a 7-tuple onto @stats:
   # [ usr,cpu,mem,totcpu,totmem,load1,load2]

You can use an anonymous hash as shown in sample below.

use strict;

my @stats;


foreach(@$statref) {
     printf("CPU: %s, MEM: %ul\n",$_->{CPU},$_->{MEM});

sub get_stats {
     return \@tempstat;

sub get_single_stat {
     my($record) = {
     USER => "Jason",
     CPU => "P4 5GHZ",
     MEM => 1073741824,
     TOT_CPU => 1,
     TOT_MEM => 4294967296,
     LOAD1 => 1,
     LOAD2 => 2,
     return $record;

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.