我知道哈希中不可能有重复的密钥,但这就是我的数据:
Key Value
SETUP_FACE_PROT great
SETUP_FACE_PROT great2
SETUP_FACE_PROT great3
SETUP_FACE_PROT great3
SETUP_ARM_PROT arm
SETUP_FOOT_PROT foot
SETUP_FOOT_PROT foot2
SETUP_HEAD_PROT goggle
我想连接重复键的值,用*
字符分隔。例如,这就是我想要输出的样子:
SETUP_FACE_PROT'=great*great2*great3',
SETUP_ARM_PROT='arm',
SETUP_FOOT_PROT='foot*foot2',
SETUP_HEAD_PROT='google'
这就是我到目前为止试图解决问题的方法:
foreach my $key ( sort keys %stuff )
{
print "$key=\'", join( "*", @{ $stuff{$key} } ), "\'\n";
}
但是不是打印结果,而是如何将它存储在变量中以便我可以将它传递给另一个子程序?我正在尝试创建一个看起来像这样的新字符串:
$newstring="
SETUP_FACE_PROT='great*great2*great3',
SETUP_ARM_PROT='arm',
SETUP_FOOT_PROT='foot*foot2',
SETUP_HEAD_PROT='google' "
答案 0 :(得分:2)
您无法复制密钥,您可以创建数组哈希。
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my %stuff;
while (<DATA>) {
my ( $key, $value ) = split;
push( @{ $stuff{$key} }, $value );
}
print Dumper \%stuff;
foreach my $key ( sort keys %stuff ) {
print "$key=\'", join( "*", @{ $stuff{$key} } ), "\'\n";
}
__DATA__
SETUP_FACE_PROT great
SETUP_FACE_PROT great2
SETUP_FACE_PROT great3
SETUP_FACE_PROT great3
SETUP_ARM_PROT arm
SETUP_FOOT_PROT foot
SETUP_FOOT_PROT foot2
SETUP_HEAD_PROT goggle
编辑:
根据要求将其转换为字符串:
my $results;
foreach my $key ( sort keys %stuff ) {
$results .= "$key=\'". join( "*", @{ $stuff{$key} } ). "\'\n";
}
print $results;
或者使用print
仍然使用文件句柄:
my $results;
open ( my $output, '>', \$results );
foreach my $key ( sort keys %stuff ) {
print {$output} "$key=\'", join( "*", @{ $stuff{$key} } ), "\'\n";
}
close ( $output );
print $results;
答案 1 :(得分:0)
最后我得到了答案。
use Data::Dumper;
my %stuff;
use Text::CSV;
my $csv = Text::CSV_XS->new ({ binary => 1, eol => $/ });
my $filenamex = 'duplicate2.csv';
$checkstring ='';
open(my $datab, '<', $filenamex) or die "Could not open '$filename' $!\n";
$i=1;
my %datan;
while (my $linea = <$datab>)
{
chomp $linea;
@fieldsx = split ",",$linea;
$key = $fieldsx[0];
$value = $fieldsx[1];
# print $key;
push( @{ $stuff{$key} }, $value );
}
foreach my $key ( sort keys %stuff )
{
$checkstring = $checkstring.','.$key.'='. join( "*", @{ $stuff{$key} } );
}
print $checkstring;