perl - 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
解决方案
看看这是否适合你。
由于在您的输入文件中,第 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
推荐阅读
- javascript - IONIC 5 / Angular 9 在原生构建中延迟加载特定组件
- sql - Oracle SQL - WHERE 子句
- swift - 如何为 UIViewController.view 中也具有 UITapGestureRecognizer 的 UIView 挑选和操作 UITapGestureRecognizer?
- azure - 创建具有受限权限的 kubeconfig
- python - 如何将列表传递给函数?
- reactjs - 使用 create-react-app 通过 npx 安装 React 应用程序时出错
- jquery - stackblitz 示例无法按预期工作
- c# - 如何在 C# 中的用户控件 ِDLL 上捕获表单?
- elasticsearch - 如何在 Windows 中从 ./bin/elasticsearch 运行 elasticsearch 文件
- python - Django - 仅显示特定的 JSON 部分