Re: the way to get current index of an array



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";
}


On Feb 27, 2006, at 11:07 PM, <zhao_bingfeng@xxxxxxxxxxxxx> <zhao_bingfeng@xxxxxxxxxxxxx> wrote:

hi, perlers,
Is there a simple way to get the current index of an array in loop statement? the procondition is you cannot get this information from array element. For example

#!usr/bin/perl
my @arr = qw/a b c d e/;
for(@arr)
{
print "The No.?? element is $_\n";
}

-----------------------------------------------
Life is a different teacher...
It doesn't teach lessons, and then keep exams...
It keeps the exams first and then teaches the lessons.





Relevant Pages

  • Re: [fitsbits] CRPIX clarification
    ... the proposed changes to the new draft FITS ... array indices} that range in value from 1 to NAXISj on axis j. ... Integral pixel coordinate values coincide with the corresponding array ... If anyone objects to the use of the phrase "regular lattice ...
    (sci.astro.fits)
  • Re: Class and inheritance
    ... > pick the first on the list that fits. ... #using poss for possibilities, bad choice ... we're depending on the order of the array called "a". ...
    (comp.lang.ruby)
  • Re: newbee need help with code
    ... > Because of probably compatible reasons does the array in VBNet create two ... > One that fits the one indexer commands. ... > are forever -1 and start always with zero. ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Organizing data for readability and efficiency
    ... the performance of single look-ups into each (rather than by whether the nature of your data best fits an array or best fits a hash), then I say you are engaging in micro-optimization. ... The difference between array access and hash access is small enough that if you are concerned about it, only actual tests on actual data will be satifactory. ...
    (comp.lang.perl.misc)
  • Re: Array Formula Help -IF / Else clause?
    ... I'm just getting to grips with Array formulae, and one of the formula I ... Creates (and sums) an array of 1s for every ... Isn't the second IF basically the ELSE clause of the first IF? ... I don't understand how this fits my usual ubderstanding of the ELSE ...
    (microsoft.public.excel)