Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!ucbvax!iwarp.intel.com!news From: merlyn@iwarp.intel.com (Randal L. Schwartz) Newsgroups: comp.lang.perl Subject: Re: Binary fixed-length records Message-ID: <1991Apr24.001205.10345@iwarp.intel.com> Date: 24 Apr 91 00:12:05 GMT References: <1991Apr23.202307.2454@kfw.COM> Sender: news@iwarp.intel.com Reply-To: merlyn@iwarp.intel.com (Randal L. Schwartz) Organization: Stonehenge; netaccess via Intel, Beaverton, Oregon, USA Lines: 53 In-Reply-To: dan@kfw.COM (Dan Mick) In article <1991Apr23.202307.2454@kfw.COM>, dan@kfw (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). Yeah, do something like: $stbuf_def="ccCCCCCCSSII"; # unpack codes for struct $streclen = length(pack($stbuf_def, ())); # length of above in bytes while (read(STDIN, $buf, $streclen) == $streclen) { @fields = unpack($stbuf_def, $buf); # process $buf } This presumes that you don't *really* need the full power of the <> construct... if you do, it'd be a bit trickier. | If I could get the book, I would... (What stops you? :-) print pack("c*",unpack("c*","Just another Perl hacker,")) -- /=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\ | on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III | | merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn | \=Cute Quote: "Intel: putting the 'backward' in 'backward compatible'..."====/