Re: the way to get current index of an array





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



Relevant Pages

  • Re: Looking for a function that will count the first instance of a
    ... are four occurrences of Bob in the array. ... The item that repeats 4 times sums to 1. ... sum of these values becomes the count of unique items. ... blanks to be counted as a unique item. ...
    (microsoft.public.excel.worksheet.functions)
  • 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: To declare or not to declare
    ... Professional Excel Development.. ... whereas for the dictionary this array must created. ... IF you need a 1 dimensional array of unique items ... > projects reference. ...
    (microsoft.public.excel.programming)
  • Re: Looking for a function that will count the first instance of a
    ... are four occurrences of Bob in the array. ... sum of these values becomes the count of unique items. ... The reason for the error is blank cells in the full range A1:A20. ... blanks to be counted as a unique item. ...
    (microsoft.public.excel.worksheet.functions)
  • Re: Looking for a function that will count the first instance of a
    ... are four occurrences of Bob in the array. ... sum of these values becomes the count of unique items. ... blanks to be counted as a unique item. ...
    (microsoft.public.excel.worksheet.functions)