Path: utzoo!attcan!uunet!zaphod.mps.ohio-state.edu!sdd.hp.com!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: Help a perl apprentice Message-ID: <10101@jpl-devvax.JPL.NASA.GOV> Date: 25 Oct 90 07:24:03 GMT References: <18840001@hp-lsd.COS.HP.COM> <10080@jpl-devvax.JPL.NASA.GOV> <1990Oct25.063526.1571@vlsi-mentor.jpl.nasa.gov> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 43 In article <1990Oct25.063526.1571@vlsi-mentor.jpl.nasa.gov> dave@vlsi-mentor.jpl.nasa.gov (David Hayes) writes: : lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) writes: : >In general, use of index variables (such as $i) is a warning sign that : >there's a better way to do it in Perl. : : Really? Please enlighten me.... : : I want to process an array of stuff @stuff. Lets say that I want to : do a "tolower" on each element of stuff (an array of text strings). : : The current way I do this is (yes I am a C programmer to the core): : : for($i=0; $i<$#stuff; $i++) { : $stuff[$i] =~ tr/A-Z/a-z/; : } : : Is there a better way? Yes. There are some iterators that cause the loop variable to refer to each array element directly, much like a C programmer would use a pointer to iterate through an array, only without having to dereference anything. You can simply say foreach $elem (@stuff) { $elem =~ tr/A-Z/a-z/; } or, more briefly, for (@stuff) { # equivalent to "foreach $_ (@stuff)" tr/A-Z/a-z/; } or even more briefly, grep(tr/A-Z/a-z/, @stuff); The other place that index variables pop up unnecessarily is when people write linear searches down a numerically indexed array, when they should be using associative arrays to do a direct lookup, or using one of the other built-in searching mechanisms. Larry