Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MultiDimensional array Input to Single array in Perl

I’ve the below Input and the expected output.

Input : [undef,[0,1],2]
Expected Output : [0,1,2]

Code I’ve written:

use Data::Dumper;
my $input=[undef,[0,1],2];
my @arr=@{$input};
@arr = grep {defined} @arr;
my @arrnew;
foreach my $value (@arr){
  if (ref $value    eq 'ARRAY') {
    push @arrnew,@{$value};
  } else {
    push @arrnew,$value;
  }
}
print Dumper(@arrnew);

Question:
Although, this gives me the correct output, would like to know if any simpler way of doing this in perl.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can roll it all into a single expression using map and grep.

use strict;
use warnings;

my $foo = [undef,[0,1],2];
my @bar = map { ref eq 'ARRAY' ? @$_ : $_ } grep defined, @$foo;

The map acts like your foreach loop and produces a new list on the way out, which gets assigned to a new array @bar. The grep you had already used, but I’ve changed it to use expression syntax rather than block syntax.

Note this only works for one level of depths.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading