Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!clyde.concordia.ca!nstn.ns.ca!news.cs.indiana.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: Strange while behaviour in sub ? Message-ID: <11323@jpl-devvax.JPL.NASA.GOV> Date: 6 Feb 91 01:41:10 GMT References: <1991Feb06.011642.14065@sdd.hp.com> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 36 In article <1991Feb06.011642.14065@sdd.hp.com> ken@sdd.hp.com (Ken Stone) writes: : Can anyone explain why this program works as it does ? When I run it : as "./tp 1 2 3", I get : : Using while loop: : Got /dev/ptypc and /dev/ttypc : Got /dev/ptypd and /dev/ttypd : Got /dev/ptype and /dev/ttype : : Using foreach loop: : Got /dev/ptypc and /dev/ttypc : Got /dev/ptypc and /dev/ttypc : Got /dev/ptypc and /dev/ttypc : : which seems really odd ... how in the heck is the while loop remembering : where it was in the expansion every time its called ? We have : put enough debug in to convince ourselves that its almost like the expansion : is in a static of some sorts ? Try running "./tp -v 1 2 3" to see what I : mean. Yes, has a built-in state, just as has a built-in state. The reason your foreach example didn't show this was that it evaluates in an array context, which returns all the values. Saying "while ()" supplies a scalar context, so it's going to return the filenames one by one. The has no idea it's being called within a while loop, so exiting the loop doesn't reset it, just as exiting "while ()" doesn't reset the file pointer back to the beginning of the file. is unlike in that it does reset when you try to read past the end of the list, whereas the file will just stay at EOF. (However, <> resets to redo @ARGV or STDIN in the same way.) The each() function works similarly--it has a built-in iterator that returns false only once before starting over. Larry