我有一个看起来像
的字符串This is sentence one.%%%0.3%%%0.6%%%This is sentence two.%%%0.4%%%0.9%%%
等。百分号只是作为分隔符,我可以根据需要进行更改。
我最终需要这样的事情:
{
'This is sentence one' => [0.3, 0.6],
'This is sentence two' => [0.4, 0.9]
}
我可以将它拆分成数组或散列没有问题,唯一能给我带来麻烦的是将每个第一个段作为键,而将每个其他段作为数组的元素。了解perl,这可能是一种非常有效的方法,可以在一行中完成!
答案 0 :(得分:5)
您需要将数据拆分为一个数组并一次性取出三个项目,使用三个中的第一个作为键,其余部分用于数组引用
喜欢这个
use strict;
use warnings 'all';
use Data::Dump;
my $str = 'This is sentence one.%%%0.3%%%0.6%%%This is sentence two.%%%0.4%%%0.9%%%';
my %data;
{
my @data = split /%%%/, $str;
while ( @data >= 3) {
my @item = splice @data, 0, 3;
$data{ shift @item } = \@item;
}
}
dd \%data;
{
"This is sentence one." => [0.3, 0.6],
"This is sentence two." => [0.4, 0.9],
}