我也遇到相同的问题,因此我使用了此解决方案。它很有帮助,但是当所有值都是标量但我的程序同时包含数组和标量值时,它很有用。因此我能够打印标量值,但无法打印数组值。请建议我们需要添加什么?
码:
#!/grid/common/bin/perl
use warnings;
require ("file.pl");
while (my ($key, $val) = each %hash)
{
print "$key => $val\n";
}
Run Code Online (Sandbox Code Playgroud)
非标量值需要取消引用,否则您将只打印出这些数据结构ARRAY(0xdeadbeef)或HASH(0xdeadbeef)带有这些数据结构的内存地址。
充分阅读《 Perl数据结构食谱》:perldoc perldsc 以及Perl参考:perldoc perlref
由于您未提供数据,因此下面是一个示例:
#!/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'";
}
}
Run Code Online (Sandbox Code Playgroud)
输出量
baz => [ 1,2,3 ]
qux => {
a => 123
b => 234
}
foo => bar
Run Code Online (Sandbox Code Playgroud)
对于更复杂的结构,您将需要递归。
Data::Printer 对于转储复杂的结构很有用。
| 归档时间: |
|
| 查看次数: |
386 次 |
| 最近记录: |