Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Find Index value of a specific element in an array

by l.frankline (Hermit)
on Jan 03, 2006 at 05:57 UTC ( [id://520502]=perlquestion: print w/replies, xml ) Need Help??

l.frankline has asked for the wisdom of the Perl Monks concerning the following question:

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.

Replies are listed 'Best First'.
Re: Find Index value of a specific element in an array
by bobf (Monsignor) on Jan 03, 2006 at 06:16 UTC
Re: Find Index value of a specific element in an array
by Samy_rio (Vicar) on Jan 03, 2006 at 06:01 UTC

    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 finding index number in an array

    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
by grinder (Bishop) on Jan 03, 2006 at 10:49 UTC
    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

Re: Find Index value of a specific element in an array
by holli (Abbot) on Jan 03, 2006 at 10:43 UTC
    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 number of modules that deal with roman numbers on CPAN.


    holli, /regexed monk/

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://520502]
Approved by gopalr
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2024-04-20 15:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found