Kris1511
Kris1511

Reputation: 300

Using join to concatenate array values

I have array values that is getting returned from SQL object.

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

gives

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

I need to create string from this array: 8853, 15141.

my $inVal = join(',', map { $_->[0] }, @$keys);

my $inVal;
foreach my $result (@$keys){
    $inVal .= $result->[0];
}

my $inVal = join(',', @$keys);

Value i get is ARRAY(0x5265498),ARRAY(0x52654e0). I think its reference to the array. Any idea what am I missing here?

Upvotes: 0

Views: 330

Answers (2)

ikegami
ikegami

Reputation: 385506

Don't pass arrays to Dumper; it leads to confusing output. $VAR1 is not a dump of @keys, it's a dump of $keys[0]. Instead, you should have done

print(Dumper(\@keys));

This would have given

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

The code you want is

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

That said, it appears that ->SelectAllArrayRef returns a reference to the result, and so it should be called as follows:

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

For this,

print(Dumper($keys));

outputs

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

And you may use either of the methods you used in your question.

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

Upvotes: 2

xxfelixxx
xxfelixxx

Reputation: 6592

The first version should work for you:

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

8853,15141

Upvotes: 2

Related Questions