Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: transforming XY data to X and Multiple Y column data?

by perlpie (Beadle)
on Sep 27, 2010 at 03:09 UTC ( #862147=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://862147]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (1)
As of 2022-01-20 00:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (56 votes). Check out past polls.

    Notices?