size of reference

J

jtbutler78

I have a reference to an array ($ref). Can I get the size in order to
loop without dereferencing $ref?

I would like to achive this but it seems like it is an extra step to
dereference it.
@array = @$ref;

for $i ( 0 .. $#array) ...
 
J

jtbutler78

Before dereferencing, I was trying something like ${#$ref} which I
understand now why it wasnt working. Thanks.
 
B

Ben Morrow

[quoting fixed. please quote correctly]

Quoth "[email protected] said:
Before dereferencing, I was trying something like ${#$ref} which I
understand now why it wasnt working. Thanks.

If you read perlreftut, you will find 'Use Rule 1' (Rule 1 for using
references): You can always use an <array> reference, in curly braces,
in place of the name of an <array>. So:

$#array # a normal array
$#{$aref} # an arrayref

There are some circumstances where you can omit the braces, but as with
parens, if in doubt put them in.

Ben
 
O

octomancer

I have a reference to an array ($ref). Can I get the size in order to
loop without dereferencing $ref?

I would like to achive this but it seems like it is an extra step to
dereference it.
@array = @$ref;

for $i ( 0 .. $#array) ...

That's a C way of iterating over an array. It is more perlish to use

foreach my $element (@$ref) {
# do some stuff ... note $element is an alias for the array element
# and any change to $element is changing the array itself
}
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top