CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Frequently Asked Questions:
How can I manipulate fixed-record-length files?

 



Jasmine
Administrator

Jan 26, 2001, 10:04 AM

Post #1 of 1 (1765 views)
How can I manipulate fixed-record-length files? Can't Post

(From the Perl FAQ)

How can I manipulate fixed-record-length files?

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:

Code
    # 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.



 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives