首页 > 解决方案 > Perl对字符串中不同字符的split函数的使用

问题描述

我需要正则表达式的字符串如下:

colour -name red -value 8,0,2 -code 0
colour -name blue -value 9 -code 1
colour -name yellow -value 7,3,2.5 -code 1

所需的输出是颜色名称和值的哈希

red 8,0,2 blue 9 yellow 7,3,2.5

一段代码:

#/usr/perl;

my %result = {};
my @word = split ' ', $line ; #$line has each of the line of data that is read from text
$result{$word[2]} = $word[4];

但这并没有为有逗号的值提供所需的输出。TIA。

所需输出

ITEMS

red 8,0,2 blue 9 yellow 7,3,2.5

获得的输出

ITEMS

red 8 0 2 blue 9 yellow 7 3 2.5

标签: perl

解决方案


看看这是否适合你。

由于在您的输入文件中,第 3 和第 5 个字段分别是颜色名称和颜色值,我们将这些内容存储到一个数组中。

push(@contents, $words[2]);
push(@contents, $words[4]);

之后,我们将数组内容连接到标量变量以适合单元格。

my $string = join(' ', @contents);

下面是脚本:

use strict; 
use warnings;
use Data::Dumper;
use Text::CSV_XS qw( csv );

my (@words, @contents) = [];

while(<DATA>){
    @words = split / /, $_;
    push(@contents, $words[2]);
    push(@contents, $words[4]);
}

my $string = join(' ', @contents);
print $string;

#Write content to CSV file
my $out_file = "out.csv";
open( my $fh, '>:encoding(UTF-8)', $out_file )
    or die "Could not open file '$out_file'";

my $csv = Text::CSV_XS->new;

#Header
$csv->combine( "ITEMS" );   
print $fh ($csv->string,"\n");

#print cell content
$csv->combine( $string );
print $fh ($csv->string,"\n");
close $fh;

__DATA__
colour -name red -value 8,0,2 -code 0
colour -name blue -value 9 -code 1
colour -name yellow -value 7,3,2.5 -code 1

推荐阅读