http://qs321.pair.com?node_id=862147


in reply to transforming XY data to X and Multiple Y column data?

The key is to figure out how you would do this without code. What things did you iterate through in what order when you formulated your desired output? Take careful note and then codify that process. This gives your desired output:

#!/usr/bin/perl use warnings; use strict; my $id; my %data; my %seen; while (<main::DATA>) { chomp; next unless /\S/; if (/\A#(id\d+)\z/) { $id = $1; $seen{'id'}{$id} = 1; } elsif (/\A(\d+)\s+(\d+)\z/) { die "no #id found before line: '$_'" unless $id; $seen{'key'}{$1} = 1; $data{$1}{$id} ||= []; push(@{$data{$1}{$id}}, $2); } else { die "unrecognized line: '$_'"; } } my ($width) = (sort {$b <=> $a} map { length } map { keys %$_ } values + %seen); my @ids = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { /id(\d+)/; [$_, $1] } keys %{$seen{'id'}}; print join(' ', map { sprintf "%${width}s", $_ } '', @ids), "\n"; for my $i (sort keys %{$seen{'key'}}) { while (keys %{$data{$i}}) { print join(' ', map { sprintf "%${width}s", $_ } $i, map { exi +sts($data{$i}{$_}) && @{$data{$i}{$_}} ? shift @{$data{$i}{$_}} : '' } keys %{$seen{'id'}}), "\n"; for my $id (keys %{$data{$i}}) { delete $data{$i}{$id} unless @{$data{$i}{$id}}; } } } __DATA__ #id1 1 90 2 80 3 70 #id2 1 70 2 40 2 40 3 20 4 5 #id3 0 0 0 0 0 0