pansywhacker
pansywhacker

Reputation: 23

Flatten part of an array in Perl?

Basically when I use Data::Dumper I get

$VAR1 = [
          '63',
          'Joe',
          'Bloggs',
          '8-Mon',
          'FAU70',
          8
        ];
$VAR2 = 'Bye';

But what I want to get is

$VAR1 = 'Joe Bloggs 8-Mon';
$VAR2 = 'Bye';

Any ideas as to how I can process to the array to only contain one value which used to be several values from it?

Thanks!

Upvotes: 0

Views: 163

Answers (3)

Miller
Miller

Reputation: 35208

If you want all of your array references listed as strings, you simply need to convert them:

use strict;
use warnings;

use Data::Dumper;

my @array = (['63', 'Joe', 'Bloggs', '8-Mon', 'FAU70', 8], 'Bye');

print Dumper(map {ref $_ ? "@$_" : $_} @array);

Outputs:

$VAR1 = '63 Joe Bloggs 8-Mon FAU70 8';
$VAR2 = 'Bye';

However, I would suggest looking into Data::Dump as an alternative to Data::Dumper if your goal is just tighter output:

use strict;
use warnings;

my @array = (['63', 'Joe', 'Bloggs', '8-Mon', 'FAU70', 8], 'Bye');

use Data::Dump;
dd @array;

Outputs:

([63, "Joe", "Bloggs", "8-Mon", "FAU70", 8], "Bye")

Upvotes: 1

John C
John C

Reputation: 4396

You can pick the parts of the array you want using a slice [1..3] then join them into one string using join like this:

my $a = [ '63', 'Joe', 'Bloggs', '8-Mon', 'FAU70', 8 ];
my $var1 = join ' ', @$a[1..3];
my $var2 = 'bye';
print "$var1 $var2\n";

Output:

Joe Bloggs 8-Mon bye

Upvotes: 1

anurag
anurag

Reputation: 202

suppose you have the array in variable @array like

my @array=(['63','Joe','Bloggs','8-Mon','FAU70',8],'Bye');

Dumper on this array structure works like this:

$VAR1 = [
          '63',
          'Joe',
          'Bloggs',
          '8-Mon',
          'FAU70',
          8
        ];
$VAR2 = 'Bye';

use this to get what you want:

map{$_=join(" ",@$_[1..4]) if(ref $_ eq 'ARRAY');} @array;

Now dumper will print like this:

$VAR1 = 'Joe Bloggs 8-Mon FAU70';
$VAR2 = 'Bye';

Upvotes: 3

Related Questions