in reply to construct a matrix by different intervals
Interesting problem. One key is to use grep to filter a range to generate entries just for the ids that have been given. Because you don't know what ids you will end up with until all the data has been parsed, you need to generate the table data as a second step. Consider:
use warnings; use strict; my %data; my %ids; while (<DATA>) { chomp; my ($rid, $start, $end) = split; push @{$data{$rid}}, [$start, $end]; @ids{$start, $end} = (); } my @idList = sort {$a <=> $b} keys %ids; for my $rid (keys %data) { my @pairs = @{$data{$rid}}; my %fields; $data{$rid} = []; @fields{grep exists $ids{$_}, $_->[0] .. $_->[1]} = () for @pairs; @{$data{$rid}} = map {exists $fields{$_}} @idList; } my $format = '%-3s' . ('%3d ' x keys %ids) . "\n"; printf $format, 'ID', sort {$a <=> $b} keys %ids; printf $format, $_, @{$data{$_}} for sort keys %data; __DATA__ A 1 2 A 7 10 A 15 20 B 3 5 B 11 15 C 5 10 D 10 20
Prints:
ID 1 2 3 5 7 10 11 15 20 A 1 1 0 0 1 1 0 1 1 B 0 0 1 1 0 0 1 1 0 C 0 0 0 1 1 1 0 0 0 D 0 0 0 0 0 1 1 1 1
|
|---|