# Thread: accessing elemnts in a array

1. ## accessing elemnts in a array

how to access the mid element in an array in perl?

2. ## Re: accessing elemnts in a array

sorry i don't have any knowledge about pearl this time

3. ## Re: accessing elemnts in a array

Hi Bvani,

I think, You have posted your query in a wrong forum. Better, post it in appropriate forum.

Regards,
Ganesh

4. ## Re: accessing elemnts in a array

Hi,

I am sorry. It was my mistake. I though this is a QTP forum

Regards,
Ganesh

5. ## Re: accessing elemnts in a array

its ok no probs it happens to every one sometimes.....

ok guys here is my answer which i have given in one of my interview... but the interviewer was not satisfied he was asking me if there were any direct funtions to do the same.

step one
sort the array in the ascending order

step two
obtain the first and last values to variables
\$low = \$a[0];
\$high = \$#a;

step three
add the first and last element and divide by 2 and obtain the int() value of the result
\$mid = int((\$low + \$high)/2);

step four
\$a[\$mid] is the middle element of the array....

anyways it would be helpful if any one can give me any other answers or any reference for the same..

6. ## Re: accessing elemnts in a array

#!/usr/bin/perl
use strict;

my @array=qw(hello World Show must go on);

my \$count=scalar @array;
print "\n Count :\$count";

print "\n \$array[(\$count/2)]";

exit;

Ans is:
Count :6
Show

7. ## Re: accessing elemnts in a array

Hi
you can do the same thing by this way also

#!/usr/bin/perl
use strict;

my @array=qw(hello World Show must go on);

print "\n \$array[((\$#array+1)/2)]";

exit;

8. ## Re: accessing elemnts in a array

Originally Posted by amitbhosale
Hi
you can do the same thing by this way also

#!/usr/bin/perl
use strict;

my @array=qw(hello World Show must go on);

print "\n \$array[((\$#array+1)/2)]";

exit;
We can also use like this,
print \$array[(scalar @array)/2];

9.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•