在perl中重写一个递归函数,以便它可以在列表上下文中使用
考虑 Moose::Cookbook 中开发的二叉树::Basics::Recipe3
要检索所有节点按顺序,我可以添加下面的子例程到 BinaryTree 包
sub pre_order {
my ($self,$aref) = @_;
push @$aref, $self->node;
pre_order($self->left,$aref) if $self->has_left;
pre_order($self->right,$aref) if $self->has_right;
}
子例程必须像这样使用:
my $btree = BinaryTree->new;
#add some nodes
#then later...
my @nodes_in_preorder;
$btree->pre_order(\@nodes_in_preorder);
我必须如何更改子例程才能使用如下语法:
my @nodes_in_preorder = $btree->pre_order();
以便能够执行
for ($btree->pre_order()) { #bla bla }
稍后的操作。
这有道理吗,还是我太迂腐了?
Consider the binary tree developed in Moose::Cookbook::Basics::Recipe3
To retrieve all nodes in preorder, I could add the following subroutine to the BinaryTree package
sub pre_order {
my ($self,$aref) = @_;
push @$aref, $self->node;
pre_order($self->left,$aref) if $self->has_left;
pre_order($self->right,$aref) if $self->has_right;
}
The sub would have to be used like this:
my $btree = BinaryTree->new;
#add some nodes
#then later...
my @nodes_in_preorder;
$btree->pre_order(\@nodes_in_preorder);
How would i have to change the subroutine to be able to use syntax like the below:
my @nodes_in_preorder = $btree->pre_order();
in order to be able to do things like
for ($btree->pre_order()) { #bla bla }
later on.
Does this make sense, or am I being to pedantic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
How about:
您可以只更改调用者:
或者简单地更改代码,如下所示:
无需将数组引用传递给外部调用;将自动创建一个,因此您的代码将正常工作(TM):
You could just change the caller:
Or simply change the code like so:
No need to pass an array reference to the outer call; one will be created automatically, so your code will Just Work (TM):