in reply to Re^3: Finding the index of a specific element in an array.
in thread Finding the index of a specific element in an array.

for my $i (0 .. $#array) { next unless $array[$i] == 7; say "The index is $i"; }

You may quibble that the use of $#array is itself an artifact of the method I've chosen to solve the problem (and I can agree), but there's less synthetic code in this version. Certainly there's iteration and incrementing, but when Perl handles that and the programmer doesn't have to, there's less synthetic code.

Replies are listed 'Best First'.
Re^5: Finding the index of a specific element in an array.
by BrowserUk (Patriarch) on Jan 25, 2012 at 02:41 UTC

    I down voted this because: once you add code to remember the index for use after the loop -- and omit the say :

    my $pos; for my $i (0 .. $#array) { next unless $array[$i] == 7; $pos = i; last; } ## do something with $pos.

    -- your code is at least as synthetic (by the standard of mjd's articles) as JavaFan's, if not more so:


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

      ... once you add code to remember the index for use after the loop -- and omit the say ...

      Sure, but that's different than the code JavaFan posted. If I were to write code to save the index after the loop, I'd write it more like the code you wrote (minus the potential infinite loop) or with something from one of the List::*Util family, like other people wrote.

      Even so, it's still less synthetic once you count tokens and the possibility of writing the wrong code.

Re^5: Finding the index of a specific element in an array.
by JavaFan (Canon) on Jan 25, 2012 at 10:41 UTC
    I'm curious to find out why you consider this to be 'natural' code which actually describes and solves the problem in hand, but using a C-style loop to be showing an artifact of the particular method that you have chosen to solve the problem.

      The C-style loop describes how to iterate. The other loop doesn't.

        It doesn't? Since when is (0 .. $#array) free to return the numbers in a non-consecutive order? Perlop describes it as:
        In list context, it returns a list of values counting (up by ones) from the left value to the right value.
        How's that different from for (my $i = 0; $i < @array; $i++) which also says to count by one, from the left value up to the right value?