Вопрос

When you dump your array with:

use Data::Dumper;
@arr=('a','b','c');
print Dumper @arr;

you get something like this:

$VAR1 = 'a';
$VAR2 = 'b';
$VAR3 = 'c';

Is possible to get something like this:

$VAR0 = 'a';
$VAR1 = 'b';
$VAR2 = 'c';

EDIT:

So far I have end up with this one-liner:

perl -lane 'if ($_=~/VAR([0-9]+) = (.*)/) {print "VAR" . ($1-1) . "=" . $2} else {print $_}'

It works as post processing script which decrement the number after VAR. But as you can see it wont produce correct output when you have element like this:

VAR7=$VAR2->[1];

Can I somehow extend this one-liner?

Это было полезно?

Решение

The Dump method takes an optional second array ref where you can specify the desired variable names in the output:

my @arr   = ('a', 'b', [qw(d e f)]);
my @names = map "VAR$_", 0 .. $#arr;

print Data::Dumper->Dump(\@arr, \@names);

Output:

$VAR0 = 'a';
$VAR1 = 'b';
$VAR2 = [
  'd',
  'e',
  'f'
];

You might also take a look at Data::Printer. I've never used it, but it seems more oriented to the visual display of data structures.

Другие советы

Whatever you are trying to do with $VARx, it isn't a good idea. How about just dumping \@arr instead of @arr?

use Data::Dumper;
@arr=('a','b','c');
print Dumper \@arr;

producing:

$VAR1 = [
          'a',
          'b',
          'c'
        ];

You can play around with some of the options (see: http://perldoc.perl.org/Data/Dumper.html)

#!/usr/bin/perl
use warnings;
use strict; 
use Data::Dumper;
$Data::Dumper::Terse = 1; # This will print out just your output (in structure)
$Data::Dumper::Pad  = 'YOUR-PREFIX = '; # This prefixes your output with whatever you want

my @arr=('a','b','c');

print Dumper @arr;

Outputs:

YOUR-PREFIX = 'a'
YOUR-PREFIX = 'b'
YOUR-PREFIX = 'c'

I had a similar need as in the question - I had incoming data with a fixed array, and wanted to know whether the correct indexes are referenced. From the original question, the part about the inner arrays does not seem to be answered, thus maybe this will help somebody.

For an inner array, I'm not aware of a way to do this in a tree, but for a single array just dereference it:

print Dumper(@{$hash->{stuff}->{fields}});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top