Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Array indices

by jkahn (Friar)
on Sep 14, 2002 at 05:53 UTC ( #197804=note: print w/ replies, xml ) Need Help??


in reply to Array indices

Your indices function sounds sorta like the smart match code that I heard theDamian talk about at his Perl6 talk -- well, at least knowing whether "heimer" is in the list.

Of course, you could write your own indices() function pretty quickly, using a sort of modification of the Schwartzian Transform (I actually have tested this, on a few cases, but let me know if I've missed anything):

sub indices ($@) { # note the prototype has target, then list my $target = shift; my (@list) = @_; my $index = 0; map { $_->[1] } grep { $_->[0] eq $target } map { [$_ , $index++] } @list; }

I'm sure some wizard out there could tighten this up, but I think it's pretty clear what I'm aiming at.


Comment on Re: Array indices
Select or Download Code
Re^2: Array indices
by Aristotle (Chancellor) on Sep 14, 2002 at 06:00 UTC
    I wouldn't use a prototype here. They're much more headache than they're usually worth.
    sub indices { my $match = shift; my $i = 0; map { $i++; $_ eq $match ? $i : () } @_ }

    Returning an empty list in the map callback causes that iteration to disappear from the result list. This is useful because you can use it as a surrogate grep that allows you to return something other than what your input was.

    Update: removed ->[0] copy paste remainder from code.

    Update 2: the following is more idiomatic and pretty much makes having a separate sub useless. We're back to grep too:

    sub indices { my $match = shift; grep $_[$_] eq $match, 0 .. $#_ }

    Makeshifts last the longest.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://197804]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2014-07-11 03:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (218 votes), past polls