I also faced the same issue and I used this solution . It helped a lot, but it is useful when all values are scalar but my program contains both array and scalar values. so I am able to print scalar values but unable to print array values. Please suggest what we need to add?
Code:
#!/grid/common/bin/perl
use warnings;
require ("file.pl");
while (my ($key, $val) = each %hash)
{
print "$key => $val\n";
}
Non-scalar values require dereferencing, otherwise you will just print out ARRAY(0xdeadbeef)
or HASH(0xdeadbeef)
with the memory addresses of those data structures.
Have a good read of Perl Data Structure Cookbook: perldoc perldsc as well as Perl References: perldoc perlref
Since you did not provide your data, here is an example:
#!/usr/bin/env perl
use warnings;
use strict;
my %hash = ( foo => 'bar',
baz => [ 1, 2, 3 ],
qux => { a => 123, b => 234 }
);
while (my ($key, $val) = each %hash) {
my $ref_type = ref $val;
if ( not $ref_type ) {
# SCALAR VARIABLE
print "$key => $val\n";
next;
}
if ('ARRAY' eq $ref_type) {
print "$key => [ " . join(',', @$val) . " ]\n";
} elsif ('HASH' eq $ref_type) {
print "$key => {\n";
while (my ($k, $v) = each %$val) {
print " $k => $v\n";
}
print "}\n";
} else {
# Otherstuff...
die "Don't know how to handle data of type '$ref_type'";
}
}
Output
baz => [ 1,2,3 ]
qux => {
a => 123
b => 234
}
foo => bar
For more complicated structures, you will need to recurse.
Data::Printer
is useful for dumping out complicated structures.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.