0

Hi I have have function which returns a reference to an array like so:

sub get_values{
.
.
.
return(\@array)
}

I copy this into another array :

@my_val = &get_values(...);

The Dumper output of this is something like:

$VAR1 = [ '1','2',...]

Now I need to combine 2 of these, but when I do

@combined = (@my_val,@my_val_2);

I get

$VAR1 = [ '1','2',...]
$VAR2 = [ '11','22',...]

I need it to combine in one element like:

$VAR1 = [ '1','2',...,'11','22',...]

How can I do this?

Codename
  • 452
  • 3
  • 15

2 Answers2

1

You are storing an array reference to an array and you don't dereference the array. The fix will be to store it to a scalar and dereference them.

$my_val = get_values(...);

$my_val_2 = get_values(...);

@combined = (@$my_val, @$my_val_2);

A custom example would be

$my_val = [1,2,3];

my $my_val_2 = [4,5,6];

my @combined = (@$my_val, @$my_val_2); # dereference the array and they get flattened automatically

print "@combined"; # 1 2 3 4 5 6
xtreak
  • 1,376
  • 18
  • 42
1

If your function is returning a reference, be prepared to take it as reference, either by dereferencing returning value,

my @my_val = @{ get_values(...) };
..
my @combined = (@my_val, @my_val_2);

or by storing reference into plain scalar,

my $aref = get_values(...);
..
my @combined = (@$aref, @$aref2);
mpapec
  • 50,217
  • 8
  • 67
  • 127
  • 2
    Also get rid of `&` when calling functions if you don't have strong reason to do so. http://stackoverflow.com/a/8915304/223226 – mpapec Nov 06 '14 at 06:26