使用join来连接数组值

时间:2017-07-21 22:55:51

标签: arrays perl

我有从SQL对象返回的数组值。

$VAR1 = [ [ '8853' ], [ '15141' ] ];

给出

8853, 15141

我需要从这个数组中创建字符串:my $inVal = join(',', map { $_->[0] }, @$keys); my $inVal; foreach my $result (@$keys){ $inVal .= $result->[0]; } my $inVal = join(',', @$keys);

ARRAY(0x5265498),ARRAY(0x52654e0)

我获得的价值是{ "date_created": "2013-12-16T16:15:23.514136", "type": "payment.created", "data": { "action": "pay", "actor": { "about": "No Short Bio", "date_joined": "2011-09-09T00:30:51", "display_name": "Andrew Kortina", "first_name": "Andrew", "id": "711020519620608087", "last_name": "Kortina", "profile_picture_url": "", "username": "kortina" }, "amount": null, "audience": "public", "date_completed": "2013-12-16T16:20:00", "date_created": "2013-12-16T16:20:00", "id": "1312337325098795713", "note": "jejkeljeljke", "status": "settled", "target": { "email": null, "phone": null, "type": "user", "user": { "about": "No Short Bio", "date_joined": "2011-09-09T00:30:54", "display_name": "Shreyans Bhansali", "first_name": "Shreyans", "id": "711020544786432772", "last_name": "Bhansali", "profile_picture_url": "", "username": "shreyans" } } } } 。我认为它对数组的引用。知道我在这里缺少什么吗?

2 个答案:

答案 0 :(得分:2)

第一个版本适合您:

my $arr = [ [ '8853' ], [ '15141' ] ];
my $values = join(',', map { $_->[0] } @$arr);
print $values . "\n";

8853,15141

答案 1 :(得分:2)

不要将数组传递给Dumper;它导致令人困惑的输出。 $VAR1不是@keys的转储,而是$keys[0]的转储。相反,你应该已经完成​​了

print(Dumper(\@keys));

这可以给出

$VAR1 = [ [ [ '8853' ], [ '15141' ] ] ];

您想要的代码是

join ',', map { $_->[0] }, @{ $keys[0] };

也就是说,->SelectAllArrayRef似乎返回对结果的引用,因此应按如下方式调用:

my $keys = $db_obj->SelectAllArrayRef($sql); 

为此,

print(Dumper($keys));

输出

$VAR1 = [ [ '8853' ], [ '15141' ] ];

您可以使用您在问题中使用的任何一种方法。

join ',', map { $_->[0] }, @$keys;