Andrej Kastrin schreef:

> I need to re-sort a set of data. I think that the below example is
> self explained; so which Perl structure should I use to handle this
> dataset?
>
> Thanks in advance for any suggestion, Andre
>
>
> 2;John;Apple;Banana
> 3;Andrew;Pear;Apple;Melon;Orange
> 8;Susan;Pear;Melon
>
> 2;John;Apple
> 2;John;Banana
> 3;Andrew;Pear
> 3;Andrew;Apple
> 3;Andrew;Melon
> 3;Andrew;Orange
> 8;Susan;Pear
> 8;Susan;Melon

This looks like a normalization step. I assume the first shape is in a
csv-like-file?

See `perldoc perldsc`.

The Persons could be put in their own table: 2 => John, 3 => Andrew,
etc.
The Fruits too, it all depends on how deep you want (or need) to go.
The data structure for your 2nd shape could be an array of arrays.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @fruit    = qw( Apple Banana Pear Melon Orange );

my @person   = ();
$person[ 2 ] = 'John';
$person[ 3 ] = 'Andrew';
$person[ 8 ] = 'Susan';

my @data     = ();
$data[ 0 ]   = [ $person[2], [ $fruit[0]
                             , $fruit[1]
                             ]
               ];
$data[ 1 ]   = [ $person[3], [ $fruit[2]
                             , $fruit[0]
                             , $fruit[3]
                             , $fruit[4]
                             ]
               ];
$data[ 2 ]   = [ $person[8], [ $fruit[2]
                             , $fruit[4]
                             ]
               ];

print Data::Dumper->Dump( [    [EMAIL PROTECTED]   ]
                        , [ qw( *data ) ]
                        );

my @new = ();

$new[0] = [ 2, 0 ];
$new[1] = [ 2, 1 ];
$new[2] = [ 3, 2 ];
# etc.

print Data::Dumper->Dump( [ map { [ $$_[0]
                                  , $person[$$_[0]]
                                  , $fruit [$$_[1]]
                                  ]
                                }
                            @new
                          ]
                        , [ qw( *new ) ]
                        );


(I couldn't get that last Dump right, it says 'VAR2' where it should
continue 'new'.)

Do you need to answer questions like: What Fruit does Andrew have? Which
Persons have a Pear? For that you could use a key on Person, and a key
on Fruit, which means Hashes. The best structure is the one that
produces your answers.

-- 
Affijn, Ruud

"Gewoon is een tijger."


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to