- 论坛徽章:
- 307
|
本帖最后由 sunzhiguolu 于 2016-07-16 11:24 编辑
回复 7# mswsg
试下,
- #!/usr/bin/perl
- use strict;
- use warnings;
- my ($offset, @aData, %hMap) = 0;
- while (<DATA>){
- my @aLine = split;
- if (!@aData){
- $aData[$offset] = [@aLine];
- $hMap{$_} = $offset for @aLine;
- next;
- }
- my @aPos;
- if (@aPos = map {exists $hMap{$_} ? $hMap{$_} : ()} @aLine){
- if (@aPos == 2 and $aPos[0] ne $aPos[-1]){
- @aPos = @aPos[-1, 0] if ($aPos[0] > $aPos[-1]);
- push (@{$aData[$aPos[0]]}, map {$hMap{$_} == $aPos[0] ? () : do {$hMap{$_} = $aPos[0]; $_}} @aLine);
- push (@{$aData[$aPos[0]]}, map {$hMap{$_} == $aPos[0] ? () : do {$hMap{$_} = $aPos[0]; $_}} @{$aData[$aPos[-1]]});
- splice (@aData, $aPos[-1], 1);
- next;
- }
- push (@{$aData[$aPos[-1]]}, map {exists $hMap{$_} ? () : do {$hMap{$_} = $aPos[-1]; $_}} @aLine);
- next;
- }
- $aData[++$offset] = [@aLine];
- $hMap{$_} = $offset for @aLine;
- }
- print "@$_\n" for @aData;
- __DATA__
- A B
- C A
- D C
- E F
- N G
- C N
复制代码 perl abc.pl
--------------------------------
A B C D N G
E F
|
|