perl 子程序返回数组和 str 但它们正在合并 [英] perl subroutine returning array and str but they are getting merged
问题描述
sub process_feed {
my ($line) = @_;
my @lines;
my $last_received = "";
while (1) {
if ($line =~/^{(.*?)}(.*)/) {
push @lines, $1;
$line = $2;
} else {
$last_received = $line;
last;
}
}
print "sending back @lines, $last_received\n";
return (@lines, $last_received);
}
my (@lines, $leftover) = process_feed("{hi1}{hi2}{hi3");
print "got lines: @lines\n";
print "got last_recevied, $leftover\n";
输出:
sending back hi1 hi2, {hi3
got lines: hi1 hi2 {hi3
got last_recevied,
预期:
sending back hi1 hi2, {hi3
got lines: hi1 hi2
got last_recevied, {hi3
为什么 $last_recevied
会合并到 @lines
?
我如何在外部函数中拆分它们?
why did $last_recevied
get merged to @lines
?
how do i split them in the outer func?
推荐答案
一个函数返回一个平面列表.如果数组在被分配的变量列表中排在第一位,则整个列表都会进入该数组.所以在
A function returns a flat list. If an array is first in the list of variables being assigned to, the whole list goes into that array. So in
my (@lines, $leftover) = process_feed("{hi1}{hi2}{hi3");
@lines
获取子返回的所有内容.
the @lines
gets everything that the sub returned.
解决方案
返回对数组的引用和一个标量,因此分配给两个标量
Return a reference to an array along with a scalar, so assign to two scalars
sub process_feed {
# ...
return \@lines, $last_received;
}
my ($rlines, $leftover) = process_feed("{hi1}{hi2}{hi3");
print "got lines: @$rlines\n";
总的来说,我会推荐这种方法.
I would recommend this approach, in general.
由于总是返回$last_received
,所以交换返回和赋值的顺序
Since $last_received
is always returned, swap the order in the return and assignment
sub process_feed {
# ...
return $last_received, @lines;
}
my ($leftover, @lines) = process_feed("{hi1}{hi2}{hi3");
由于分配是先分配给标量,因此只将返回值中的一个值分配给它,然后其他值进入下一个变量.这里是数组@lines
,它接受所有剩余的返回.
Since the assignment is to a scalar first only one value from the return is assigned to it and then others go into next variables. Here it is the array @lines
, which takes all remaining return.
这篇关于perl 子程序返回数组和 str 但它们正在合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!