【问题标题】:How do I initialize HoH from arrays of variable size如何从可变大小的数组初始化 HoH
【发布时间】:2011-06-12 20:32:31
【问题描述】:

我需要帮助弄清楚如何适应 $hash {$i} 加载不同大小的 @headers 数组的情况。 使用严格; 使用警告;

    my $file = "list.csv";

    open (FILE,"$file") || die "Can't open file: $!\n"; 
    my (@lines) = <FILE>; 
    close(FILE);

    my @headers = split(',',$lines[0]);#split up header line

    my %hash;
    for (my $i=1; $i < scalar(@lines); $i++)
    {
        my @strings = split(',',$lines[$i];

# NEED help here
        $hash{$i} = {
            $headers[0] => $strings[0],
            $headers[1] => $strings[0],
            $headers[2] => $strings[0],
            $headers[3] => $strings[0],
            $headers[4] => $strings[0],
            $headers[5] => $strings[0]
            };

    }

在 scalar(@headers)=5,6,7 ... 等情况下,有没有办法在索引处加载哈希?是否有类似的程序等价物......

$hash{$i} = {
        $headers[0] => $strings[0],
              ...
        $headers[n] => $strings[n]
        };

$hash{$i} = {@headers => @strings);

【问题讨论】:

标签: arrays perl hash


【解决方案1】:

你想要的成语是:

@{ $hash{$i} }{ @headers } = @strings;

这被称为slicing

鉴于您正在读取 CSV 数据,您可能会查看一些 CPAN 模块,例如 Text::CSV

【讨论】:

  • +1 - 始终使用 CPAN - 您不想为正确解析 CSV 文件而头疼。永远。
【解决方案2】:

TIMTOWTDI

#!/usr/bin/perl

use strict;
use warnings;

my $file = "list.csv";

# Use lexical filehandles, not globals; use 3-arg open; don't quote filename
open ( my $fh, '<', $file ) or die "Can't open file: $!\n";
my( @lines ) = <$fh>;
close( $fh );

# split takes a regex; also, notice the shift
my @headers = split( /,/, shift @lines );

my %hash;

# Use perly for loops here
foreach my $i ( 0..$#lines )
# This works, too
#for my $i ( 0..$#lines )
{
    # split takes a regex
    my @strings = split( /,/, $lines[$i] );

    # One way (probably best)
    @{ $hash{$i} }{ @headers } = @strings;
    # Another way
    #$hash{$i} = { map { $headers[$_] => $strings[$_] } ( 0 .. $#strings ) };
    # Another way
    #$hash{$i}{ $headers[$_] } = $strings[$_] = for(0..$#strings);

}

#use Data::Dumper;
#print Dumper \%hash;

但是是的,使用Text::CSV(或更快的Text::CSV_XS)甚至比尝试自己手动拆分 CSV 更好(如果有空格会发生什么?如果引用字段和/或标题会发生什么?这是一个已解决的问题。)

【讨论】:

    猜你喜欢
    • 2021-06-08
    • 1970-01-01
    • 2014-11-29
    • 2023-02-23
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多