Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.jpl.nasa.gov (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: Binary fixed-length records Message-ID: <1991Apr24.002156.7082@jpl-devvax.jpl.nasa.gov> Date: 24 Apr 91 00:21:56 GMT References: <1991Apr23.202307.2454@kfw.COM> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 49 In article <1991Apr23.202307.2454@kfw.COM> dan@kfw.com (Dan Mick) writes: : Often, I want to dump a file full of fixed-length records. The one way I've : been using is : : #!/usr/local/bin/perl : : $stbuf_def="ccCCCCCCSSII"; # unpack codes for struct : $streclen=20; # length of above in bytes : $/ = 0777; # slurp in the whole file : $_ = <>; # into $_ : : $inputlen = length($_); : $offset = 0; : : while ($inputlen > 0) { : $rec = substr($_, $offset, $streclen); : : : : $inputlen -= $streclen; : $offset += $streclen; : } : : : ...but it strikes me that 1) the "slurp in whole file" will fail someday, : and 2) the copy in the substr() can't be efficient. : : Anyone willing to take a crack? (I'm aware that the surrounding goo : might not be as efficient as possible; what I'm mostly worried about are : the two points above). Recalling that read actually uses stdio for efficiency, and desiring to emulate the <> semantics, which may be overkill, we get: #!/usr/local/bin/perl $stbuf_def = "ccCCCCCCSSII"; # unpack codes for struct $streclen = length(pack($stbuf_def, 0)); # length of above in bytes @ARGV = '-' unless @ARGV; foreach $file (@ARGV) { open(IN, $file) || do { warn "Can't open $file: $!\n"; next; }; while (read(IN, $_, $streclen)) { } } Larry