Re: the way to get current index of an array
- From: mlists@xxxxxxxxxxxxxxx (JupiterHost.Net)
- Date: Tue, 28 Feb 2006 11:13:53 -0600
The Ghost wrote:
sub getIndex {
my ($array, $value)=@_;
my $x=0;
foreach (@{$array}) { $_ eq $value ? return $x : $x++; } #only works if array has unique items and is slow, but could be easy if it fits your problem
#personally, I don't recommend this, but maybe it's what you were thinking of?
}
#!usr/bin/perl
my @arr = qw/a b c d e a/; #last element will list as zero!
for(@arr)
{
my $num=getIndex(\@arr, $_);
print "The No.$num element is $_\n";
}
Oi, don't do that :)
You exponentially (sort of) loop over the list by looping the list again for each item in the list.
This is efficient and fast (and easy to read and maintain)
*and* it will work with things like last(), redo(), etc...:
for my $idx (0 .. $#arr) {
print "Item number $idx is $arr[$idx]\n";
}
.
- References:
- the way to get current index of an array
- From: Zhao Bingfeng
- Re: the way to get current index of an array
- From: The Ghost
- the way to get current index of an array
- Prev by Date: CPAN for the first time
- Next by Date: Re: CPAN for the first time
- Previous by thread: Re: the way to get current index of an array
- Next by thread: upload photo
- Index(es):
Relevant Pages
|
|