CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Location of a scalar in an unknown array

 



kade
Deleted

Aug 17, 2000, 4:25 AM

Post #1 of 4 (282 views)
Location of a scalar in an unknown array Can't Post

Hi friends,
If I have an array which I don't know its lenght.And I need to know the location of a specific scalar in that array.

#Such a text file," name.txt " containing(Jim,Paul,Frank,Tim,Joe)
#suppose I don't know the content and length of this file.

But I need to know the location of "Tim" in this array.(which is 3).
What is the code?
Thanks
Kade


rGeoffrey
User / Moderator

Aug 17, 2000, 8:48 AM

Post #2 of 4 (282 views)
Re: Location of a scalar in an unknown array [In reply to] Can't Post

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


my $where = &Find_Index ('Joe', qw (Jim Paul Frank Tim Joe));
print "$where\n";
sub Find_Index {
my ($target, @array) = @_;
my $index = scalar (@array);
while ($index >= 0) {
$index--;
last if ($array[$index] eq $target);
}
return ($index);
}
</pre><HR></BLOCKQUOTE>
By starting at the end of the array and working backwards, we only have to ask the length of the array once (and can compare to 0 each time through the loop). Also the value of $index on failure is a -1 which is probably a good thing.

One warning, if 'Tim' is in the array twice, this function will only return his last appearance, not the first, or all of them.


Cure
User

Aug 17, 2000, 11:58 AM

Post #3 of 4 (282 views)
Re: Location of a scalar in an unknown array [In reply to] Can't Post

my $location = find('Tim',qw(Jim Paul Frank Tim Joe));

print "$location\n";

sub find {

my ($target, @array) = @_;
my $number = @array;

CURE: while ($number > 0) {
$number--;
last CURE if ($array[$number] eq $target);
}
$number;
}


Cure


kade
Deleted

Aug 17, 2000, 3:45 PM

Post #4 of 4 (282 views)
Re: Location of a scalar in an unknown array [In reply to] Can't Post

Thank you very much!!
Kade

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives