Home: Perl Programming Help: Advanced:
reference on reference array



gooroo175
Novice

Nov 8, 2010, 5:29 AM


Views: 4933
reference on reference array

I'm looking for a way to write the following in one line.


Code
my @refs = \($var1, $var2, $var3); 
my $refRef = \@refs;


Any ideas?


BillKSmith
Veteran

Nov 8, 2010, 12:06 PM


Views: 4928
Re: [gooroo175] reference on reference array


Code
use strict;  
use warnings;
use Data::Dumper;

my $var1 = 1;
my $var2 = 2;
my $var3 = 3;
my $refRef = [\($var1, $var2, $var3)];
print Dumper $refRef;



output:

Code
 $VAR1 = [  
\1,
\2,
\3
];





Note: the square brackets return a reference to an array.


rovf raised a good point. Line 8 of the above code is exactly what you asked for, but may not be what you need.
Good Luck,
Bill

(This post was edited by BillKSmith on Nov 9, 2010, 7:56 AM)


rovf
Veteran

Nov 9, 2010, 7:17 AM


Views: 4899
Re: [gooroo175] reference on reference array

Do you want the array to contain the values, or to conatin references to your scalar variables?


gooroo175
Novice

Nov 9, 2010, 11:01 AM


Views: 4891
Re: [rovf] reference on reference array

Thanks for the replys so far.

Actually I wanna build a function for querying a single line out of dbi. That function is supposed to call $sth->bind_columns what requires a reference to the variables to bind. I want to pass all those variable references as an array reference as one value in the call to the parent function. Would way described below work?


Code
query("select id from table where sth=?",[$req],[\($id)]); 

sub query {
my ($sql, $par, $colRef);
# first query db here
$sth->bind_columns(@$colRef);
}



rovf
Veteran

Nov 10, 2010, 3:10 AM


Views: 4868
Re: [gooroo175] reference on reference array

I think I understand. To say it otherwise: You have a set of variables $v1, $v2, $v3,...., and are looking for a neat way to construct a reference to an array containing references to variables, i.e. [\$v1,\$v2,\$v3,...]. Is this correct?

You could do it like this:

my $ref_to_array_containing_refs = map { \$_ }($v1,$v2,$v3);

The trick works, because $_ is an alias to the respective array element, not a copy.


gooroo175
Novice

Nov 10, 2010, 10:55 PM


Views: 4859
Re: [rovf] reference on reference array

You solved it! Thank it.