hide random home http://www.fmi.uni-passau.de/archive/doc/unix/perl/faq/2.16.html (Einblicke ins Internet, 10/1995)

How can I manipulate fixed-record-length files?

How can I manipulate fixed-record-length files?


    The most efficient way is using pack and unpack.  This is faster than
    using substr.  Here is a sample chunk of code to break up and put back
    together again some fixed-format input lines, in this case, from ps.

        # sample input line:
        #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
        $ps_t = 'A6 A4 A7 A5 A*';
        open(PS, "ps|");
        $_ = <PS>; print;
        while (<PS>) {
            ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
            for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
                print "$var: <", eval "\$$var", ">\n";
            }
            print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
        }