我如何匹配涉及添加功能的原始线?

时间:2014-06-03 20:12:17

标签: perl

#!/usr/local/bin/perl
my @a     = <DATA>;
my @grep  = grep { m/^a/g } @a;
my @grep2 = grep { m/^b/g } @a;
my @xx;
my @yy;

foreach (@grep) {
    my $x = (split)[1], $_;
    push( @xx, $x );
}
foreach (@grep2) {
    my $y = (split)[1], $_;
    push( @yy, $y );
}
my @mv;
my $i;
my $j;
for ( $i = 0 ; $i < @xx ; $i++ ) {
    for ( $j = 0 ; $j < @yy ; $j++ ) {
        my $m = $xx[$i] + $yy[$j];
        push( @mv, $m );
    }
}

foreach (@mv) {
    if ( $_ eq "15" ) {
        print "$grep2[$mv]\n";
    }
}
__DATA__
a 15 c
a 13 m
a 10 c 
b 2  k
b 12 m
b 13 m
b 5  v
b 5  m
b 6  h
b 15 m
b 12 v
b 21 m
b 11 q
b 9  m
b 32 w

使用'b'添加'a'的值,得到36个值。但我期待哪个值为15,而'b'打印的原始行。例子13从'a 13 m'和2'从'b 2 k'那些是答案是15我希望输出是'b 2 k'..同样

I expect output
 b 2 k
 b 5 v
 b 5 m

1 个答案:

答案 0 :(得分:1)

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

my %data;

while (<DATA>) {
    my ($pre, $num, $suffix) = split;
    push @{ $data{$pre} }, [$num, $suffix];
}

for my $aref (@{ $data{a} }) {
    for my $bref (@{ $data{b} }) {
        print "b @$bref\n" if $aref->[0] + $bref->[0] == 15;    
    }   
}