in reply to Finding values position in array

Anytime you find yourself writing:

for (list) { last if (); }

Think grep


s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}

Replies are listed 'Best First'.
Re^2: Finding values position in array
by GrandFather (Saint) on Apr 14, 2008 at 00:15 UTC

    unless 'list' is large or the test has side effects or is expensive.

    grep processes all of the list whereas the for loop stops on the first successful match.


    Perl is environmentally friendly - it saves trees
Re^2: Finding values position in array
by cosmicperl (Chaplain) on Apr 14, 2008 at 02:24 UTC
    I though of grep but when I checked the doc page (which is thin to say the least) I couldn't see a way of using it. Would you be kind enough to give an example?
      ben@Tyr:~$ perl -we'@list = 1..24; print "'4' found at \$list[$_]\n" f +or grep { $list[$_] =~ /4/ } 0 .. $#list' 4 found at $list[3] 4 found at $list[13] 4 found at $list[23] ben@Tyr:~$ perl -we'@list = 1..24; print "'4' found at \$list[$_]\n" f +or grep { $list[$_] =~ /^4$/ } 0 .. $#list' 4 found at $list[3]

      The first example matches '4' anywhere in the element; the second one is a precise match.

      
      -- 
      Human history becomes more and more a race between education and catastrophe. -- HG Wells