Perl:更改散列为键的数组项

时间:2011-06-15 12:34:03

标签: perl hash

我的perl有问题。我给一个数组加了一把钥匙。现在我想为每个键更改数组中的内容。但我无法弄清楚它是如何工作的:

open(DATEBOOK,"<sample.file");

@datebook = <DATEBOOK>;

$person = "Norma";

foreach(@datebook){
    @record = ();
    @lines = split(":",$_);

        $size = @lines;
        for ($i=1; $i < $size; $i++){
            $record[$i-1] = $lines[$i];
        }
    $map{$lines[0]}="@record";  

}

for(keys%map){ print $map{$_}};

日记本文件:

Tommy Savage:408.724.0140:1222 Oxbow Court, Sunnyvale,CA 94087:5/19/66:34200
Lesle Kerstin:408.456.1234:4 Harvard Square, Boston, MA 02133:4/22/62:52600
JonDeLoach:408.253.3122:123 Park St., San Jose, CA 94086:7/25/53:85100
Ephram Hardy:293.259.5395:235 Carlton Lane, Joliet, IL 73858:8/12/20:56700
Betty Boop:245.836.8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
William Kopf:846.836.2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
Norma Corder:397.857.2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
James Ikeda:834.938.8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000
Lori Gortz:327.832.5728:3465 Mirlo Street, Peabody, MA 34756:10/2/65:35200
Barbara Kerz:385.573.8326:832 Ponce Drive, Gary, IN 83756:12/15/46:268500

我尝试了$map{$_}[1],但这不起作用。任何人都可以给我一个如何工作的例子:)?

谢谢!

2 个答案:

答案 0 :(得分:4)

首先,use strictuse warnings。总是

假设你想要的是数组的哈希值,可以这样做:

use strict;
use warnings;

open my $datebookfh, '<', 'sample.file' or die $!;
my @datebook = <$datebookfh>;

my %map;
foreach my $row( @datebook ) { 
    my @record = split /:/, $row;
    my $key = shift @record;   # throw out first element and save it in $key

    $map{$key} = \@record;
}

您可以使用Data::Dumper

来测试您是否具有正确的结构
use Data::Dumper;
print Dumper( \%map );

\运算符需要引用。 Perl中的所有哈希和数组都包含标量,因此复合结构(例如数组的哈希)实际上是引用到数组的哈希值。引用就像一个指针。

在继续之前,你应该看看:

答案 1 :(得分:3)

其他人给了你很好的建议。这是另一个需要考虑的想法:将数据存储在散列哈希中,而不是数组散列中。它使数据结构更具沟通性。

# Include these in your Perl scripts.
use strict;
use warnings;

my %data;

# Use lexical files handles, and check whether open() succeeds.
open(my $fh, '<', shift) or die $!;

while (my $line = <$fh>){
    chomp $line;
    my ($name, $ss, $address, $date, $number) = split /:/, $line;
    $data{$name} = {
        name    => $name,
        ss      => $ss,
        address => $address,
        date    => $date,
        number  => $number,
    };
}

# Example usage: print info for one person.
my $person = $data{'Betty Boop'};
print $_, ' => ', $person->{$_}, "\n" for keys %$person;