字符串连接perl到变量

时间:2015-03-11 07:11:15

标签: perl concatenation

我有一个这样的字符串:

my $masterP = "A:B:C a:b:c a:c:b A:C:B B:C:A";
my (@scen) = split (/ /, $$masterP);
foreach my $key (@scen) {
my ($string1, $string2, $string3) = split (/:/,$key);
my $new = "${string1}_${string2}";
my $try .= $try."$new";
}
print "$try\n";

我期待$ try打印:A_B a_b a_c A_C B_C(带空格)但它不起作用。有人可以解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

这将满足您的需求。

use strict;
use warnings;

my $masterP = "A:B:C a:b:c a:c:b A:C:B B:C:A";

my @scen = split ' ', $masterP;
my @try = map { join '_', (split /:/)[0,1] } @scen;
my $try = "@try";
print "$try\n";

<强>输出

A_B a_b a_c A_C B_C

答案 1 :(得分:0)

请始终使用Strict和Warnings获取有价值的代码:

use strict;
use warnings;

my $masterP = "A:B:C a:b:c a:c:b A:C:B B:C:A";
my @scen = split(/ /, $masterP); my $try;
foreach my $key (@scen) {
my ($string1, $string2, $string3) = split (/:/,$key);
my $new = "${string1}_${string2}";
$try .= " $new";
$try=~s/^\s//;  chomp($try);
}
print "$try\n";

可能对你有用。