Find Index value of a specific element in an array
l.frankline
created: 2006-01-03 00:57:11

Dear Monks,

I am trying to find out the index value of a specific element in an array. I have tried below code and it is working fine,
but it doesn't seems to be pretty well, because the code contains too many lines.

Is there any shortest and easiest way.

@roman = qw(i ii iii iv v vi vii viii ix x xi xii xiii xiv xv xvi xvii xviii xix xx);
$indx=0;
for (@roman) {
     $indx++;
     print "Index value for $_ is: $indx" if ($_ eq 'xiv');
}

Results:

Index value for xiv is: 14

Thanks in advance
Regards,
Franklin.

Don't put off till tomorrow, what you can do today.

Re: Find Index value of a specific element in an array
created: 2006-01-03 01:01:33

the code contains too many lines

Hi, here is an alternate way to do this, but as far as efficency i am not sure.

my ($index) = grep $roman[$_] eq "xiv", 0..$#roman;

Also take a look at this [id://461243]

Regards,
Velusamy R.


eval"print uc\"\\c$_\""for split'','j)@,/6%@0%2,`e@3!-9v2)/@|6%,53!-9@2~j';

Re: Find Index value of a specific element in an array
created: 2006-01-03 01:16:33

Take a look at Limbic~Region's excellent Tutorial entitled Getting Matching Items From An Array, in which he discusses several solutions including the grep method described above and one that uses List::Util's first function.

Also, don't forget about node 3989 and the node 1843 section, which has a large collection of posts in the node 1824 category, including node 113951 and node 62913.

Re: Find Index value of a specific element in an array
created: 2006-01-03 05:43:10
I don't know if that roman number example is just academic (in that case the following won't help much), but
use Roman;
print "value for XIV is ", arabic("xiv");
There a [cpan://Roman|number of modules] that deal with roman numbers on CPAN.


holli, /regexed monk/
Re: Find Index value of a specific element in an array
created: 2006-01-03 05:49:12
Is there any shortest and easiest way.

In this specific domain, yes there is:

use Math::Roman;
print Math::Roman->new(uc $_)->as_number, "\n"
    for @roman;

That's maybe not quite what you had in mind, but I throw it in for completeness.

• another intruder with the mooring in the heart of the Perl

perlmonks.org content © perlmonks.org and bobf, grinder, holli, l.frankline, Samy_rio

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03