Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting size of array parameter passed as a reference

Status
Not open for further replies.

LucL

Programmer
Jan 23, 2006
117
US
Hi,

How can I obtain the size of an array that was passed as a reference.

ex:

&something(\@v1,\@v2);

sub something{
my($arr1,$arr2)=@_;

#get size of arr1?
}

I know I can loop through all the items by setting up a foreach(@$arr) but the regular old $# doesn't seem to work.

I also don't want to make a copy of this as an array, I want to keep it as a reference.

Thanks!
 
Get the count just like you would a normal array - by calling the array in scalar context.

Code:
my @v1 = qw(a b c);
my @v2 = qw(1 2 3 4 5);

&something(\@v1,\@v2);

sub something{
  my($arr1,$arr2)=@_;
  my $count = @{$arr1}; # call the array in scalar context.  
  print $count;
}
 
You can still use the $#array with references:
Code:
my @a = ('one', 'two', 'three');
print "Main: $#a\n";

test(\@a);

sub test {
    my $ref = shift;
    print "Sub: $#$ref\n";
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top