【发布时间】:2015-05-02 13:32:19
【问题描述】:
我正在使用 Perl 提取 bitbucket 存储库列表。来自 bitbucket 的响应将仅包含 10 个存储库和一个标记,用于下一页将有另外 10 个存储库等等......(他们称之为分页响应)
所以,我编写了一个递归子程序,如果存在下一页标记,它会调用自己。这将持续到最后一页。
这是我的代码:
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
use LWP::UserAgent;
use JSON;
my @array;
recursive("my_bitbucket_url");
foreach ( @array ) { print $_."\n"; }
sub recursive
{
my $url = $_[0];
### here goes my LWP::UserAgent code which connects to bitbucket and pulls back the response in a JSON as $response->decoded_content
### hence, removing this code for brevity
my $hash = decode_json $response->decoded_content;
#print Dumper ($hash);
foreach my $a ( @{$hash->{values}} )
{
push @array, $a->{links}->{self}->{href};
}
if ( defined $hash->{next})
{
print "Next page Exists \n";
print "Recursing with $hash->{next} \n";
recursive( $hash->{next} );
}
else
{
print "Last page reached. No more recursion \n"
}
}
现在,我的代码工作正常,它列出了所有的 repos。
问题:
我不确定我使用上面的变量 my @array; 的方式。我已经在子程序之外定义了它,但是,我直接从子程序访问它。不知怎的,我觉得这是不对的。
那么,在这种情况下,如何使用递归子例程追加到数组。我的代码是遵守 Perl 道德规范还是真的很荒谬(但因为它有效而正确)?
更新
在遵循@ikegami、@Sobrique 和@Hynek -Pichi- Vychodil 的建议后,我提供了以下代码,它使用while 循环并避免recurssion。
这是我的思考过程:
- 定义一个数组
@array。 - 使用初始位桶 URL 调用子例程
call_url并将响应保存在$hash - 检查
$hash中的下一页 页面标记- 如果存在 next 页面标记,则将元素推送到
@array并使用新标记调用call_url。这将通过while循环完成。 - 如果 next 页面标记确实 不 存在,则将元素推送到
@array。期间。
- 如果存在 next 页面标记,则将元素推送到
- 打印
@array内容。
这是我的代码:
my @array;
my $hash = call_url("my_bitbucket_url ");
if (defined $hash->{next})
{
while (defined $hash->{next})
{
foreach my $a ( @{$hash->{values}} )
{
push @array, $a->{links}->{self}->{href};
}
$hash = call_url($hash->{next});
}
}
foreach my $a ( @{$hash->{values}} )
{
push @array, $a->{links}->{self}->{href};
}
foreach (@array) { print $_."\n"; }
sub call_url
{
### here goes my LWP::UserAgent code which connects to bitbucket and pulls back the response in a JSON as $response->decoded_content
### hence, removing this code for brevity
my $hash = decode_json $response->decoded_content;
#print Dumper ($hash);
return $hash;
}
肯定想知道这看起来是否还可以,或者还有改进的余地。
【问题讨论】:
-
if defined后跟while defined是多余的 - 如果条件相同,如果条件不成立,while将绕过。 -
呃。 “哈希”和“数组”是变量的可怕名称。 “repo”或者更好的“current_repo”怎么样?