Search code examples
perldata-dumper

print array of arrays with a separator


I have written a simple perl script:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

$Data::Dumper::Pair     = '';
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Terse    = 1;

my @A=( [ 1,2 ],[ 3,4,5 ], [ 6,7,8 ]);
print Dumper(@A);

The output i get is :

> ./temp9.pl
[
          1,
          2
        ]
[
          3,
          4,
          5
        ]
[
          6,
          7,
          8
        ]

But what i need is the elements(arrays) to be separated with a comma , in between them. I am much familiar in using Data:Dumper. Is there any fix for this? The expected output is :

[
          1,
          2
        ],
[
          3,
          4,
          5
        ],
[
          6,
          7,
          8
        ]

Anothere question i have is is there any way in data dumper where i can add some text before each element in an array?for example here in array of array , can i add "xyz" before the opening brace of each array?


Solution

  • UPDATED#2

    Try with print 'my $aRef = ', Dumper(\@A), ";";. It will print like this:

    my $aRef = [
      [
        1,
        2
      ],
      [
        3,
        4,
        5
      ],
      [
        6,
        7,
        8P
      ]
    ]
    ;
    

    If You want to change the output of Dumper you can redirect the stdout to a variable (see open).

    print map { "Something $_\n" } split "\n", Dumper(\@A);
    

    Output:

    Something [
    Something   [
    Something     1,
    Something     2
    Something   ],
    Something   [
    Something     3,
    Something     4,
    Something     5
    Something   ],
    Something   [
    Something     6,
    Something     7,
    Something     8
    Something   ]
    Something ]