[英]Split a string into a hash of arrays in perl
I have a string that looks like 我有一个看起来像的字符串
This is sentence one.%%%0.3%%%0.6%%%This is sentence two.%%%0.4%%%0.9%%%
etc. The percent signs just act as delimiters and I can change them as need be. 等等。百分号仅用作分隔符,我可以根据需要更改它们。
I need to end up with something like this: 我需要结束这样的事情:
{
'This is sentence one' => [0.3, 0.6],
'This is sentence two' => [0.4, 0.9]
}
I can split it into an array or hash no problem, the only bit that's giving me trouble is making every first segment a key and every other segment an element of an array. 我可以将其拆分为一个数组,也可以毫无问题地进行哈希处理,唯一麻烦的是使每个第一个段成为键,而每个其他段都成为数组的元素。 Knowing perl, there's probably a very efficient way to do this in one line!
知道了perl,可能有一种非常有效的方法可以一站式完成!
You will need to split the data into an array and pull items off three at a time, using the first of the three for a key and the remainder in an array reference 您将需要将数据拆分为一个数组,然后一次从三个项中取出项,使用三个项中的第一个作为键,其余的则作为数组引用
Like this 像这样
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],
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.