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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array Question 1

Status
Not open for further replies.

jmdc

MIS
Feb 2, 2001
19
US
Is there a quick way to find out the last element of an array? for example if I opened up a directory for reading and put the contents into an array. How can I find out how many elements there are in that array? Once I get that information I want to put that value into a variable. If I'm not making sense please let me know.
 
>Is there a quick way to find out the last element of an array?

my $last_ele = @array[-1];

>How can I find out how many elements there are in that array?

my $num_ele = $#array + 1; #for @array ---
cheers!
san.
 
sorry about that, it should be:

my $last_ele = $array[-1];
---
cheers!
san.
 
@array = ("one", "two", "three");

$removed = pop(@array);

# "$removed" is now equal to "three"
# but the array is equatl to ("one", "two")
# to replace it use the following code

push(@array, $removed);

# the array is equatl to ("one", "two", "three")


##############


For the question of counting each addition to the array just set $i = "0" and then have the string "$++;" in the loop each time you add a string to the array.
 
Accessing the array in scalar context will give you the number of values in the array
Code:
$numvals = scalar(@array);
Or just
Code:
$numvals = @array;
@array is in scalar context here because the lvalue ($numvals) is a scalar

In addition [tt]$#array[/tt] gives you the index of the last value in the array.
Example usage:
Code:
foreach $i (0..$#array) {

    print $array[$i];
}
jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top