Parse record
#!/usr/bin/perl
# input: string, hash { field1 => length1, field2 => length2, ... }
# output: hash { field1 => value1, field2 => value2, etc }
sub extract2 {
print "extract2 ...\n";
my $str = shift;
my $fieldlist = shift;
# construc matching pattern
my $patstr = "";
while( my ( $fieldname, $fieldlength ) = each %$fieldlist ) {
$patstr .= "(.{$fieldlength})";
} # end while
# match it
if ($str =~ m/$patstr/) {
my @values = $str =~ /$patstr/;
# create the output
my $i = 0;
while( my ( $fieldname, $fieldlength ) = each %$fieldlist ) {
$record{$fieldname} = $values[$i++];
}
return \%record;
} else {
my %record = ();
return \%record;
}
}
$str = "AAABBBBCCCCCDDD";
%header = (
field1 => 3,
field2 => 4,
field3 => 5,
field4 => 4
);
$output = extract2($str, \%header);
print "outside ...\n";
for my $key (keys %$output) {
my $val = $output->{$key};
print "$key , $val \n";
}
exit 0;
