[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Interpreting a columnar text file.



>>>>> "Chaim" == Chaim Frenkel <chaimf@pobox.com> writes:

Chaim> I found this piece of code useful to generate an unpack format when I
Chaim> needed to translate a columnar text file.

Chaim> 	$fmt = "";
Chaim> 	while(<>) {chomp; $fmt |= $_};

Chaim> 	$fmt =~ y/ /X/c;
Chaim> 	$fmt =~ s/(X+\s+)/"A".(length($1)-1)."x"/ge;

It seems that "foo     bar" would be incorrectly translated to "A3xA3"
with this?  I don't think you want to collapse \s+ there.

How about this instead:

## @data = "foo  bar";
@data = `ps lww`;
$fmt = "";
for (@data) { chomp; $fmt |= $_ }
$nul = "\0" x length($fmt); # for padding
$fmt =~ s/\G(\s*)(\S+)/" x".length($1)." A".length($2)/ge;
print "fmt = <<$fmt>>\n";
for (@data) { print join "|", unpack($fmt, $nul | $_), "\n" }

-- 
Name: Randal L. Schwartz / Stonehenge Consulting Services (503)777-0095
Keywords: Perl training, UNIX[tm] consulting, video production, skiing, flying
Email: <merlyn@stonehenge.com> Snail: (Call) PGP-Key: (finger merlyn@teleport.com)
Web: <A HREF="http://www.stonehenge.com/merlyn/">My Home Page!</A>
Quote: "I'm telling you, if I could have five lines in my .sig, I would!" -- me

==== Want to unsubscribe from Fun With Perl?
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org