0

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?

4
  • How is $keys related to your $VAR1 example ? Commented Jul 21, 2017 at 23:05
  • my @keys = $db_obj->SelectAllArrayRef($sql); print Dumper @keys; Result from Dumper is $VAR1 = [ [ '8853' ], [ '15141' ] ]; Commented Jul 21, 2017 at 23:18
  • You would capture an array reference as my ($aref) = $db_obj->.... In perl, $keys and @keys are different variables (!). $keys is a scalar variable holding a value or a reference to something else. @keys is an array. See perldoc perlref for the gory details. Commented Jul 21, 2017 at 23:31
  • Your code doesn't produce the output you claim it does because @keys isn't the same as @$keys. Commented Jul 23, 2017 at 6:57

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

2

The first version should work for you:

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

8853,15141

2 Comments

Doesn't seem to be working ...:( in the context... seems to work as script thought.
@Kris1511 Then show us that context please. Edit the question and show the code that sets this up. Otherwise, your first two attempts are good (the last one would give what you show, two reference-stringifications)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.