"Paul Lalli" <> wrote:
> Jim Cook wrote:
> > > Please note that in Perl, it's far more conventional to write:
> > > for my $a (0..$max-1)
> > > than to use C-style for-loops.
>
> > Does that have a potential memory hit if $max is exceedingly large, or
> > does perl handle it gracefully?
>
> In "recent" versions of Perl, the list will be evaluated "lazilly",
> meaning that the list is not actually built up to store large amount of
> data in memory. I do not know a precise definition of "lazy" in this
> case.
>
> > If it handles it gracefully in this
> > case, is it true for all .. constructs, or does it actually generate
> > the list sometimes?
As far as I can tell, a very simple .. in a for loop is the only case where
it is lazy.
>
> I do not *believe* Perl will generate a list for anything which it can
> evaluate lazily, but I do not know that for a fact.
It depends on what you mean by "can". perl can't do things in ways other
than what it was implemented to do, so in that sense it is a practicially a
tautology that perl does lazy evaluation everywhere it can. But if by
"can" you mean "it is conceptually feasible that it could", then it isn't
lazy wherever it can be. For example, it is conceptually feasible to be
lazy in the list part of a map or a grep, or in a reverse or array slice
used in the list of foreach or map or grep, but it is not lazy in any of
these contexts.
In each case, final memory usage in KB is printed:
perl -le 'foreach (1..10_000_000) { last}; \
print +(`ps -p $$ -o rss `)[1];'
1308
perl -le 'foreach (1..10_000_000,"extra") {last}; \
print +(`ps -p $$ -o rss `)[1];'
708460
perl -le 'foreach ("extra",(1..10_000_000)) {last};\
print +(`ps -p $$ -o rss `)[1];'
708460
perl -le 'foreach (@x[1..10_000_000]) { last}; \
print +(`ps -p $$ -o rss`)[1];'
905196
perl -le 'foreach (reverse 1..10_000_000) { last};\
print +(`ps -p $$ -o rss `)[1];'
708476
perl -le 'grep /foo/, 1..10_000_000;print +(`ps -p $$ -o rss `)[1];'
1337220
perl -le 'map "", 1..10_000_000;print +(`ps -p $$ -o rss `)[1];'
917644
This is perl, v5.8.7 built for x86_64-linux
Xho
--
--------------------
http://NewsReader.Com/ --------------------
Usenet Newsgroup Service $9.95/Month 30GB