Perl:从数组中提取值对 [英] Perl: Pulling pairs of values from an array

查看:35
本文介绍了Perl:从数组中提取值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑

#!/usr/bin/perl
use strict;
use warnings;

while(<DATA>) {
  my($t1,$t2,$value);
  ($t1,$t2)=qw(A P); $value = $1 if /^$t1.*$t2=(.)/;
  ($t1,$t2)=qw(B Q); $value = $1 if /^$t1.*$t2=(.)/;
  ($t1,$t2)=qw(C R); $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

我想用优雅的循环替换存储在数组(或其他结构)中的成对的 $t1,$t2 值,如其中之一

I'd like to replace the repetition with an elegant loop over pairs of $t1,$t2 values stored in an array (or other structure) like one of

my @pairs = qw (A,P   B,Q   C,R);
my @pairs = qw (A P   B Q   C R);

我在结合 whilesplitunshift 的简短尝试中并没有取得多大成功.

I've not had much success with a brief attempt at combining while, split and unshift.

我缺少什么简洁、优雅的解决方案?

What concise, elegant solution am I missing?

附言我过去使用过哈希,但发现 %h = (A=>'P', B=>'Q', C=>'R') 语法嘈杂".扩展到三胞胎,四胞胎也很丑......

P.S. I've used hashes in the past but find the %h = (A=>'P', B=>'Q', C=>'R') syntax "noisy". It's also ugly to extend to triplets, quads ...

推荐答案

当一个 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";
}

这篇关于Perl:从数组中提取值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆