my %hash = map { $inhalt[0] => 1 } @inhalt;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
package Names; ########################################################################### # Rolf Rost, 14.2.2011 # Anonyme Array-Elemente bekommen Namen ########################################################################### use strict; # Setzt ein Array in ein Objekt um sub new{ my $class = shift; my $maps = shift; # {3 => 'Day', 4 => 'Month', 5 => 'Year'} my $aref = shift; # array als referenz von localtime, stat, etc. return if ref $maps ne 'HASH'; return if ref $aref ne 'ARRAY'; my $self = {}; for(my $i = 0; $i < scalar(@$aref); $i++){ $self->{$maps->{$i}} = $aref->[$i] if exists $maps->{$i}; } return bless $self, $class; } package main; use strict; use warnings; use Data::Dump qw(dump); # Erste Zeile sei my $z1 = "Name,Vorname,Alter"; my @header = split ",", $z1; my $helper = {}; foreach my $i(0..$#header){ $helper->{$i} = $header[$i]; } #print dump $helper; # { "0" => "Name", 1 => "Vorname", 2 => "Alter" } my $result = {}; my $i = 1; # Zeilennummer while(my $line = <DATA>){ chomp $line; my $o = Names->new($helper, [split ",", $line]); $result->{$i} = $o; $i++; } print dump $result; #{ # 1 => bless({ Alter => 45, Name => "Meier", Vorname => "Hans" }, "Names"), # 2 => bless({ Alter => 54, Name => "Hansel", Vorname => "Horst" }, "Names"), # 3 => bless({ Alter => 33, Name => "Horst", Vorname => "Anna" }, "Names"), #} # CSV __END__ Meier,Hans,45 Hansel,Horst,54 Horst,Anna,33
Quotewie kriege ich es hin, dass der Key "Name" die Values "Meyer" und "Schmidt" zugeweisen bekommt?
$hash{Name} = ['Vorname','Alter'];
2011-04-19T14:58:29 PETER_PAN2009Code (perl): (dl )my %hash = map { $inhalt[0] => 1 } @inhalt;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#!/usr/bin/perl use strict; use warnings; use Text::CSV; my $file='namen.csv'; open(my $fh, '<', $file) or die("ERROR open $file ($!)\n"); my $csv = Text::CSV->new (); # first line my $key_names=$csv->getline( $fh ); # Array of hashes my @data; # read File while( my $row = $csv->getline( $fh ) ) { my $value={}; $value->{$key_names->[$_]}=$row->[$_] for(0..$#$key_names); push(@data,$value); } # Formated Output use Data::Dumper; print Dumper(\@data);
1
2
3
4
5
6
7
8
9
10
11
12
$VAR1 = [
{
'Vorname' => 'Peter',
'Alter' => '56',
'Name' => 'Meyer'
},
{
'Vorname' => 'Andre',
'Alter' => '74',
'Name' => 'Schmidt'
}
];