0

我正在使用 perl 进行编程。我陷入了这样一种情况,即有一个循环从文件中获取数据,从而拆分为一个名为 data 的数组,即@data。我有一个哈希 %hash 用于直接添加数组元素而无需引用。

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

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

1 回答 1

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
于 2013-05-11T03:41:42.753 回答