且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Perl:从数组中提取值对

更新时间:2023-02-26 09:24:13

当一个 hash + each 不够好(因为

When a hash + each isn't good enough (because

  • 对列表中的第一个元素不是唯一的,或者
  • 您需要以特定顺序遍历这些对,或者
  • 因为您需要抓取三个或更多元素而不是两个,或者
  • ...),

List::MoreUtils::natatime 方法:

use List::MoreUtils q/natatime/;

while(<DATA>) {
  my($t1,$t2,$value);
  my @pairs = qw(A P B Q C R);
  my $it = natatime 2, @pairs;
  while (($t1,$t2) = $it->()) {
      $value = $1 if /^$t1.*$t2=(.)/;
  }
  print "$value\n";
}

__DATA__
A P=1 Q=2 R=3
B P=8 Q=2 R=7
C Q=2 P=1 R=3

不过,通常我只会拼接列表的前几个元素来完成这样的任务:

Usually, though, I'll just splice out the first few elements of the list for a task like this:

while(<DATA>) {
  my($t1,$t2,$value);
  my @pairs = qw(A P B Q C R);
  # could also say  @pairs = (A => P, B => Q, C => R);
  while (@pairs) {
      ($t1,$t2) = splice @pairs, 0, 2;
      $value = $1 if /^$t1.*$t2=(.)/;
  }
  print "$value\n";
}