SPUG: RE: Conserving memory

El JoPe Magnifico jope-spug at jope.net
Sun Oct 21 17:25:21 CDT 2001

On Sun, 21 Oct 2001, Jeremy Devenport wrote:
> 1) You don't need to check for defined inside a while loop condition if
> it is of the form <FILE> or $var = <FILE>. Perl does this for you.
> You can use the B::Deparse module to take the opcodes back to perl and
> look if you don't believe me. Try running perl -MO=Deparse
> comparision.txt and compare four_a and four_b before and after. Or if
> you are source code oriented look at Perl_newWHILEOP in perl's op.c.

When did that behavior change?  while(<FILE>) has always checked for
defined, but while($var=<FILE>) _used_ to check for truth instead.

> In conclusion, this was the most efficient (memory & speed) way I found
> in perl to output a file is:
> print while <FILE>;

I suspect that it'd be even faster to read in fixed-size chunks:

  syswrite(STDOUT, $_) while sysread(FILE, $_, 1024);

Which lets you skip parsing of the input for line endings, while still
saving you from slurping the whole file into memory.  Note that sysread()
and syswrite() have some gotchas associated with mixing with other IO,
e.g. print(), that I don't totally understand.  If you need to do any
other IO inside your while() loop, then the alternative is:

  print while read(FILE, $_, 1024);

I'd be interested to see benchmark comparisons. (sorry, in a rush now)

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://zipcon.net/spug/

More information about the spug-list mailing list