Home > Mobile >  How to divide an array in to two different arrays in Perl
How to divide an array in to two different arrays in Perl

Time:10-12

I have an Array of Hash, and I need to divide it into two different arrays. The array of Hash looks like this:

 [
   {
      'a'=>1
      'b'=>2
      'c'=>3
      'd'=>4
   },
   {  
      'e'=>5
      'f'=>6
      'g'=>7
      'h'=>8
   }
];

I need to divide it into two different arrays in the manner:

   [{
      'a'=>1
      'b'=>2
      'c'=>3
      'd'=>4
   }]


    [{  
      'e'=>5
      'f'=>6
      'g'=>7
      'h'=>8
   }]

I have tried the below code:

      my @new_array;
    push @new_array, [ splice @$missingSections, 0, 2 ] while @$old_array;

But this is splitting the array and merging it into the same array, which means I am getting the below output:

   [[{
      'a'=>1
      'b'=>2
      'c'=>3
      'd'=>4
   }],
   [{  
      'e'=>5
      'f'=>6
      'g'=>7
      'h'=>8
   }]]

What shall I do to get two different arrays?

CodePudding user response:

There is a range of operations supported on arrays in Perl. As for basics, we can remove and return an element from front or back, with shift or pop, and can add with unshift or push.

Then there is more, including splice you tried, and then there are libraries for more complex operations. But the basics readily solve your quest. One way

my @new_array_1 = shift @old_array;
my @new_array_2 = shift @old_array;

(An array can be simply assigned a list of elements, including just one. But if there is anything in the array then that would be all gone after such an assignment so don't forget that.)

Now @old_array is empty, if it had only those two elements, which are in the @new_array_N's.

Another, even more elemental way, is to index into the array to access individual elements and copy them to new arrays. This way @old_array would stay as it is.

Perhaps a more reasonable arrangement is to have references for these two new arrays as elements of an array, which may be what your code attempts to do. For that you only need

my @new_array = map { [ $_ ] } @old_array;

where map applies the code in the block to each element of its input (@old_array), returning a list, assigned to @new_array. That [] in the body constructs an anonymous array (reference), which is a scalar and as such can be placed on an array. The only element placed in this array-reference is the currently processed element of @old_array, available in the (ubiquitous) $_ variable.

See perlintro and perldata linked above, and links in shift. For many additional operations on lists and arrays, provided in libraries, see List::Util and List::MoreUtils for starters.

For references see perlreftut and for arrays with references see perllol (lists-of-lists) and perldsc (data structures cookbook).

CodePudding user response:

You can refer to https://perlmaven.com/hash-of-arrays for reference. You might get your answer.

  • Related