我正在尝试匹配数组中的字符串并交换相关的值。但是无法形成逻辑。
@match = (
"signal=signal_1 signal_2 signal_3",
"signal_1=signal_4 signal_5 abc",
"abc=signal_6 signal_7"
);
$i = 0;
$num = @match;
while ( $i < $num ) {
$j = $i + 1;
while( $j < $num ) {
$match[$i] =~ s/=/ /g;
$match[$j] =~ s/=/ /g;
print($match[$i]);
#print($match[$j]);
@link1 = split / /, $match[$i];
@link2 = split / /, $match[$j];
#print(@link1);
#print(@link2);
for ( $i = 0; $i <= ($#link1); $i++ ) {
if ( $link1[$i] =~ $link2[0] ) {
# here I am missing the logic to interchange
}
}
$j++;
exit;
}
$i++;
}
输出数组应为
@match = (
"signal=signal_4 signal_5 abc signal_2 signal_3",
"signal_1=signal_4 signal_5 signal_6 signal_7",
"abc=signal_6 signal_7"
);
是否可以将此数组转换为哈希并交换匹配的键和值?
答案 0 :(得分:2)
是的,使用哈希要容易得多。
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
my @match = ('signal=signal_1 signal_2 signal_3',
'signal_1=signal_4 signal_5 abc',
'abc=signal_6 signal_7');
my %symbol;
@{ $symbol{ $_->[0] } }{ split ' ', $_->[1] } = ()
for map { [ split /=/ ] } @match;
my $changed;
do {
$changed = 0;
for my $key (keys %symbol) {
for my $value (keys %{ $symbol{$key} }) {
if (exists $symbol{$value}) {
my @news = keys %{ $symbol{$value} };
for my $new (@news) {
next if exists $symbol{$key}{$new};
$changed = 1;
undef $symbol{$key}{$new};
}
}
}
}
} while $changed;
use Data::Dumper; warn Dumper \%symbol;