如何在不使用其引用的情况下将数组放入数组的哈希中

时间:2013-05-10 06:55:10

标签: arrays perl

我正在使用perl进行编程。 我陷入了一种情况,如果有一个循环从文件中摄入,从而分成一个名为data的数组,即@data。 我有一个哈希%哈希,用于直接添加数组元素而不需要引用。

在这种情况下,对于while循环,$ key在其内存中保存一个@data信息,并将其后面的所有行放入其中。请提供完美的解决方案。

while (loop in which line by line of file is been readed) {
    @data= split (/\|/, $line, -1);
    %hash{$key}= \@data;
}

1 个答案:

答案 0 :(得分:0)

#! /usr/bin/env perl
use common::sense;
use YAML 'Dump';

my %results;

sub bad {
  my @data;
  while (<DATA>) {
    chomp;
    @data = split /\|/, $_, 2;
    $results{bad}{$data[0]} = \@data;
  }
}

sub good {
  while (<DATA>) {
    chomp;
    my @data = split /\|/, $_, 2;
    $results{good}{$data[0]} = \@data;
  }
}

sub good_also {
  while (<DATA>) {
    chomp;
    /^([^|]+)/;  # pretend we're getting the key some other way
    $results{good_also}{$1} = [split /[|]/, $_, 2]
  }
}

my $data_pos = tell DATA;
bad;
seek DATA, $data_pos, 0; good;
seek DATA, $data_pos, 0; good_also;

print Dump(\%results);

say "bad purchase: ", join '|', @{$results{bad}{purchase}};
say "bad location: ", join '|', @{$results{bad}{location}};
say "bad when: ", join '|', @{$results{bad}{when}};

__DATA__
purchase|apples
location|Fiesta
when|today

输出:

---
bad:
  location: &1
    - when
    - today
  purchase: *1
  when: *1
good:
  location:
    - location
    - Fiesta
  purchase:
    - purchase
    - apples
  when:
    - when
    - today
good_also:
  location:
    - location
    - Fiesta
  purchase:
    - purchase
    - apples
  when:
    - when
    - today
bad purchase: when|today
bad location: when|today
bad when: when|today