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

Re: [Sheflug] Extracing data from a file



On Tue, 2002-04-16 at 18:00, José Luis Gómez Dans wrote:
> Hi,
>     A question for all you awk/sed/perl wizards out there. I have a
> file which has a number of records in the following fashion

How about:

--------------------------
#!/usr/bin/perl -w
use strict;

my $file = 'pathtofile';
open (DATA, "<$file") or die "Can't open $file";
my $finished = 0;
my @data;	# global bin to put records

sub getline () { my $line = <DATA>; chomp $line if (defined $line);
return $line; }

while (!$finished) {
	# Records are a hash:
	# id - the identity string
	# dunno - some value I couldn't work out ;)
	# n - number of records
	# data - arrayref to the data lines
	my ($id, %record, @datarecords) = (getline);
	if (! defined $id) { $finished = 1; next; }
	($record{id}, $record{dunno}, $record{n}) = ($id, getline, getline);
	for (my $i=0; $i<$record{n}; $i++) { push ( [at] data_records, getline); }
	$record{data} = \@data_records;
	push (@data, \%record);
}

close DATA;

# bang out records...
foreach my $record ( [at] data) {
	open (OUTPUT, ">$record->{id}") or die "Can't write to $record->{id}";
	print OUTPUT "$record->{dunno}\n$record->{n}\n";
	map { print OUTPUT "$_\n"; } ( [at] {$record->{data}});
	close (OUTPUT);
}

--------------------------

Golf, anyone?

Cheers,

Alex.

Attachment: signature.asc
Description: This is a digitally signed message part