Perl 中的字符串连接到变量

String concatenation in Perl to a variable

我有这样的字符串:

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(space),但它没有工作。如何解决?

请始终使用 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";

这将满足您的要求:

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