Mastering Perl for Bioinformatics [Electronic resources]

نسخه متنی -صفحه : 156/ 30
نمايش فراداده

2.5 Printing Complex Data Structures

Sometimes you need to look inside your complex data structures to see what the settings are. One of the most useful ways to examine a data structure is by means of the Data::Dumper module. This module comes standard with all recent versions of Perl.

Here is the summary and part of the synopsis and description as output from the perldoc Data::Dumper command:

NAME
Data::Dumper - stringified perl data structures, suitable
for both printing and "eval"
SYNOPSIS
use Data::Dumper;
# simple procedural interface
print Dumper($foo, $bar);
(...)
DESCRIPTION
Given a list of scalars or reference variables, writes out
their contents in perl syntax. The references can also be
objects.  The contents of each variable is output in a
single Perl statement.  Handles self-referential strucTures correctly.
The return value can be "eval"ed to get back an identical
copy of the original reference structure.
(...)

This output of a two-dimensional array illustrates its use:

use Data::Dumper;
$array = [  ];
# Initialize the array
for($i=0; $i < 4 ; ++$i) {
for($j=0; $j < 4 ; ++$j) {
$array->[$i][$j] = $i * $j;
}
}
# Print the array "by hand"
for($i=0; $i < 4 ; ++$i) {
for($j=0; $j < 4 ; ++$j) {
printf("%3d ", $array->[$i][$j]);
}
print "\n";
}
# Print the array using Data::Dumper
print Dumper($array);

This produces the output:

  0   0   0   0 
0   1   2   3 
0   2   4   6 
0   3   6   9 
$VAR1 = [
[
0,
0,
0,
0
],
[
0,
1,
2,
3
],
[
0,
2,
4,
6
],
[
0,
3,
6,
9
]
];

You can make a nicer display by knowing exactly what the data is and in what form to write it out. Data::Dumper can also display the data in a fairly readable format (and there are several options as to how the data is displayed). In addition, Data::Dumper allows you to dump a data structure out to a file and then read it in to another program. See the perldoc Data::Dumper manpage for more details.

You can also print out an array of arrays @array by printing each row one at a time. Remember that each row is an anonymous array, so each entry of the @array array is a reference to an anonymous array:

@array = (
[0, 0, 0, 0], 
[0, 1, 2, 3], 
[0, 2, 4, 6], 
[0, 3, 99, 9] 
);
for $anon (@array) {
print "@$anon\n";
}

See the Perl perllol reference page for more information on initializing and printing arrays of arrays.