dereference an array problem

C

craigandjeanne

Hi,

The following code, I thought, should have worked properly for looping
through an array passed as a reference to a function. But, instead I
end up with the error message: "Can't use string ("string") as an ARRAY
ref while "strict refs" in use at ./test.pl line 29, <FILE> line 2. The
following is a cut down version of the actual code.


my @list = ( 1, 2, 3 );

server_work(@list);
exit;

sub server_work {
my ($a_ref) = shift;
my $val;
foreach $val (@{$a_ref}) {
print STDOUT $val;
}
return(1);
}

What am I doing wrong?
 
C

craigandjeanne

Found my own problem :) forgot to send it as a reference to the
subroutine. Doh!

server_work(\@list);

:)
 
M

Matt Garrish

craigandjeanne said:
Hi,

The following code, I thought, should have worked properly for looping
through an array passed as a reference to a function. But, instead I
end up with the error message: "Can't use string ("string") as an ARRAY
ref while "strict refs" in use at ./test.pl line 29, <FILE> line 2. The
following is a cut down version of the actual code.


my @list = ( 1, 2, 3 );

server_work(@list);

You aren't passing an array ref here, you're passing the array.
exit;

sub server_work {
my ($a_ref) = shift;

Therefore, this assignment gets the first value of the array.
 
M

Matt Garrish

Matt Garrish said:
You aren't passing an array ref here, you're passing the array.


Therefore, this assignment gets the first value of the array.

And thanks to a slip on the keyboard off went that message. To finish, to
pass a reference use a slash in front of the array:

server_work(\@list);

Matt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top