perl使用hash来读取文件

时间:2014-05-24 10:11:16

标签: windows perl csv hash

我正在尝试在Perl中编写一个函数,它将哈希和文件名作为输入。

基本上我的哈希是这样的,例如datahash是哈希的名称,然后

datahash(Attr1) = 1
datahash(Attr2) = 5
datahash(Attr3) = 4
datahash(Attr4) = 6

我的文件是带有Attr1,Attr2的csv ..因为csv中的列名和散列的valuess是同一文件中的列号。

我的功能需要根据哈希键和值从文件中提取数据。任何线索或想法?它需要将文件的列名称与哈希匹配,找出列号,然后提取列号的值。需要提取几个列。

下面是我的代码:(不要打扰我可以放置循环的多个打印件)

my %dataHash = %{$_[0]};
my $fileName = $_[1];   
my @keys = keys %dataHash;
my @values = values %dataHash;
open my $info, $file;
while( my $line = <$info>)  
{
            my @arrdata = split(/,/, $line);
            print @arrdata[values[0]];
            print @arrdata[values[1]];
            print @arrdata[values[2]];
            print @arrdata[values[3]];
            print @arrdata[values[4]];
            print @arrdata[values[5]];          
    }

示例文件:

attr1,abc,def,ghi,attr3,attr2,attr4,attr5,attr6
1,2,3,4,5,6,7,8,9
11,12,13,14,15,16,17,18,19
11,12,13,14,15,16,17,18,19
11,12,13,14,15,16,17,18,19

所以哈希有我需要提取的列名和列号,文件是这样的。

2 个答案:

答案 0 :(得分:1)

为了帮助您入门,您可以尝试以下方法:

#! /usr/bin/perl

use warnings;
use strict;

my %dataHash;
$dataHash{Attr1} = 1;
$dataHash{Attr2} = 5;
$dataHash{Attr3} = 4;
$dataHash{Attr4} = 6;

my $fileName = 'file.csv';

my @keys = keys %dataHash;
my @values = map {$_-1} values %dataHash;

open (my $info, "<", $fileName);

while( my $line = <$info>)  
{
   chomp $line;
   my @arrdata = split(/,/, $line);
   print "@arrdata[@values]\n";
}

close($info);

答案 1 :(得分:1)

使用Text::CSV

use strict;
use warnings;

use Text::CSV;

my @rows;
my $csv = Text::CSV->new ( { binary => 1 } )
    or die "Cannot use CSV: ".Text::CSV->error_diag ();

my $fh = \*DATA; # Open a fh instead

my $header = $csv->getline( $fh );

while ( my $row = $csv->getline( $fh ) ) {
    my %hash;
    @hash{@$header} = @$row;
    push @rows, \%hash;
}
$csv->eof or $csv->error_diag();
close $fh;

use Data::Dump;
dd \@rows;

__DATA__
attr1,abc,def,ghi,attr3,attr2,attr4,attr5,attr6
1,2,3,4,5,6,7,8,9
11,12,13,14,15,16,17,18,19
11,12,13,14,15,16,17,18,19
11,12,13,14,15,16,17,18,19

输出:

[
  {
    abc   => 2,
    attr1 => 1,
    attr2 => 6,
    attr3 => 5,
    attr4 => 7,
    attr5 => 8,
    attr6 => 9,
    def   => 3,
    ghi   => 4,
  },
  {
    abc   => 12,
    attr1 => 11,
    attr2 => 16,
    attr3 => 15,
    attr4 => 17,
    attr5 => 18,
    attr6 => 19,
    def   => 13,
    ghi   => 14,
  },
  {
    abc   => 12,
    attr1 => 11,
    attr2 => 16,
    attr3 => 15,
    attr4 => 17,
    attr5 => 18,
    attr6 => 19,
    def   => 13,
    ghi   => 14,
  },
  {
    abc   => 12,
    attr1 => 11,
    attr2 => 16,
    attr3 => 15,
    attr4 => 17,
    attr5 => 18,
    attr6 => 19,
    def   => 13,
    ghi   => 14,
  },
]