Re: how do prlglobs expand (was Re: 'nobody' using sudo -- scary!)



Ben Morrow <ben@xxxxxxxxxxxx> wrote:
[please quote properly]

Quoth news1234@xxxxxxx:

What would happen if I use follwing statement in perl"

foreach my $file (</home/*/.forward>){
do_something($file);
}

would perl
- iterate through the files
- or would perl first create a list of all the files and then
iterate through them.

'foreach' always creates a list and then iterates over it.

Not always. For example, in the case of foreach (1..1e6).


- or would it hit a linit and not provide all hits.
- or does it depend on the system perl is running on

You will eventually hit the memory limit on your system, and the limit
on the size of the pointer used to index the perl stack; you won't hit
any limits before that.

You can avoid pre-creating the list by using 'while' instead:

while (my $file = </home/*/.forward>) {

On my system, and I suspect on all systems, this still pre-creates the
result set in its entirety.

For example, if I put a "last" in the while loop, the code still performed
49418 "lstat" calls before it did a single loop iteration and broke out.

Perhaps the result set is stored in a special packed structure that is more
compact than it would be in a foreach loop. But a test shows that this
effect seems small. it took 12 meg to do

while (<blah/*>) {last}

and 14.3 meg to do

foreach (<blah/*>) {last}

Where blah has 49418 files in it.

Xho

--
-------------------- http://NewsReader.Com/ --------------------
The costs of publication of this article were defrayed in part by the
payment of page charges. This article must therefore be hereby marked
advertisement in accordance with 18 U.S.C. Section 1734 solely to indicate
this fact.
.



Relevant Pages

  • Perl crash related to Tie::File and hashes
    ... crash in perl when I try to use the data later on. ... sub TIEARRAY { ... foreach my $p { ... The assignment in the last loop causes perl to crash. ...
    (comp.lang.perl.moderated)
  • Re: foreach vs. for
    ... > is in the C-style for loop ... On the other hand - and this is where it's a matter of style - any Perl ... style "foreach" loop can also be written as a C style "for". ... I *do* use "foreach" fairly often, but I always spell it out. ...
    (comp.lang.perl.misc)
  • Re: Nested loop
    ... If Synopsis 4* is to be believed, in Perl 6 there will not be a loop ... of the functionality of foreach. ...
    (perl.beginners)
  • Re: Microsoft Word and Perl
    ... foreach my $obj_Story { ... It srill gave me the same error i am not sure why it is doing that ... Perl it kind of acts really stange.. ... > That way you don't need the extra statement before the loop. ...
    (comp.lang.perl.misc)
  • Re: Nested loop
    ... William is dead, long live Bill? ... foreach and for are two names for the same thing and just as you can ... that isn't better written as a range based for loop or while loop. ... whileis more efficient in Perl. ...
    (perl.beginners)