在 Perl 中缩进和递归打印数据结构 [英] Indent and recursively print data structure in Perl
问题描述
我正在开发一个函数,该函数应该递归地解析传递给它的数据结构,然后用缩进将其打印出来.类似的东西:
I am working on a function which should recursively parse through the data structure passed into it and then print it out with indentation. Something like:
indent(foo=>{bar=>'baz'})
should print like:
foo
bar : baz
indent(foo=>[a,b,c=>'d',e])
should print like
foo
a
b
c:d
e
我在 Stack Overflow 上看到了一篇帖子,里面有一个非常相似的使用深度优先递归的场景,以及关于如何通过 Perl 数据结构进行递归的本页.
I came across a post here on Stack Overflow with a very similar scenario using depth-first recursion, as well as this page about how to recurse through a Perl data structure.
但是,我无法了解内部子组件的工作方式.此外,它不会在某些情况下缩进/打印,例如:
However, I am unable to follow how the the inner sub works. Also, it does not indent/print for certain scenarios like:
[aa,xx=>'yy',rr]
Output:
aa
xx
yy
rr
这是我尝试使用的代码:
This is the code I am trying to work with:
&expand_references2([aa,xx=>'yy',rr]);
sub expand_references2 {
my $indenting = -1;
my $inner; $inner = sub {
my $ref = $_[0];
my $key = $_[1];
$indenting++;
if(ref $ref eq 'ARRAY'){
print ' ' x $indenting;
printf("%s\n",($key) ? $key : '');
$inner->($_) for @{$ref};
}elsif(ref $ref eq 'HASH'){
print ' ' x $indenting;
printf("%s\n",($key) ? $key : '');
for my $k(sort keys %{$ref}){
$inner->($ref->{$k},$k);
}
}else{
if($key){
print ' ' x $indenting,$key,' => ',$ref,"\n";
}else{
print ' ' x $indenting,$ref,"\n";
}
}
$indenting--;
};
$inner->($_) for @_;
}
推荐答案
这个问题是基于一个错误的前提:[a, b, c =>'d', e]
只会在没有 use strict 'subs'
的情况下编译,即使这样也会引发警告
This question is based on a false premise: [a, b, c => 'd', e]
will compile only without use strict 'subs'
in place, and even then will raise a warning
未加引号的字符串可能会与未来的保留字发生冲突
Unquoted string may clash with future reserved word
等同于 [ 'a', 'b', 'c', 'd', 'e' ]
粗逗号 =>
和普通逗号的唯一区别是,如果它是一个裸字,它将隐式引用它的第一个参数
The only difference between a fat comma =>
and an ordinary comma is that it will implicitly quote its first parameter if it is a bareword
您必须始终 use strict
和使用警告'all'
在您编写的每个 Perl 程序的顶部.使用与符号 &
调用子程序也是错误的;自 22 年前 Perl 5 出现以来,这一直不是一个好的做法.无论您使用什么教程来学习 Perl,您都应该放弃它并找到更新的教程
You must always use strict
and use warnings 'all'
at the top of every Perl program you write. It is also wrong to call subroutines with an ampersand character &
; that hasn't been good practice since Perl 5 arrived twenty-two years ago. Whatever tutorial you are using to learn Perl you should drop it and find a more recent one
这篇关于在 Perl 中缩进和递归打印数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!