Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

How can I manipulate fixed-record-length files?

by faq_monk (Initiate)
on Oct 08, 1999 at 00:23 UTC ( #648=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

The most efficient way is using pack() and unpack(). This is faster than using substr() when take many, many strings. It is slower for just a few.

Here is a sample chunk of code to break up and put back together again some fixed-format input lines, in this case from the output of a normal, Berkeley-style ps:

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

We've used $$var in a way that forbidden by use strict 'refs'. That is, we've promoted a string to a scalar variable reference using symbolic references. This is ok in small programs, but doesn't scale well. It also only works on global variables, not lexicals.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
[shmem]: well finally.
[stevieb]: nice! I just finished a GPS "take me home" device last week, and did a bunch of software updates to it yesterday. I also created a pseudo chip with an Arduino to simulate an IC, where it responds to register read/writes over the I2C bus...
[stevieb]: ...from an I2C master. It's ugly and there are many changes I'm going to make, but I had not done anything like it before. It's designed for my RPi:: automated test platform; a system that does CI on *all* my RPi modules.

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2017-06-25 22:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many monitors do you use while coding?















    Results (572 votes). Check out past polls.