perl - 如何在 Perl 脚本中打印空间包含属性
问题描述
我在输入文件中有一些数据
user date="" name="" id="small"
user date="" name="" id="sample test"
user date="" name="" id="big city"
我只想从上面的文件中获取 id
代码::-
use strict;
use warnings;
my $input = "location\input.txt";
open("FH","<$input") or die;
while(my $str = <FH>)
{
my @arr = split(/ /,$str);
$arr[2] =~ s/id=//g;
$arr[2] =~ s/"//g;
print "$arr[2]\n";
}
close("FH");
输出 :
small
sample
big
注意 :: 在这里我无法打印完整的单词,如“小测试”、“大城市”
期望:我需要完整的单词“样本测试”和“大城市”任何人请帮助我
解决方案
处理带引号的字符串的一个不错的模块是Text::ParseWords
. 它也是一个核心模块,使它更加方便。您可以在此处使用它轻松地将字符串拆分为空格,然后将结果解析为哈希键。
use strict;
use warnings;
use Data::Dumper;
use Text::ParseWords;
while (<DATA>) {
chomp;
my %data = map { my ($key, $data) = split /=/, $_, 2; ($key => $data); } quotewords('\s+', 0, $_);
print Dumper \%data;
}
__DATA__
user date="" name="" id="small"
user date="" name="" id="sample test"
user date="" name="" id="big city"
输出:
$VAR1 = {
'user' => undef,
'name' => '',
'date' => '',
'id' => 'small'
};
$VAR1 = {
'name' => '',
'date' => '',
'id' => 'sample test',
'user' => undef
};
$VAR1 = {
'id' => 'big city',
'date' => '',
'name' => '',
'user' => undef
};
推荐阅读
- javascript - 如何检测鼠标是否在屏幕的某个部分?
- swift - 枚举的字符串插值产生“unknown()”字符串
- angularjs - 我需要通过页面上特定元素的代码在 Ionic 3 中显示 PopOver
- react-native - 更改片段内容 onPress
- python - 根据数据框的一行创建直方图
- django - 将 Admin ManyToManyField 提取到 CSV 文件
- c# - 以编程方式创建的用户控件的 C# Winform Click 事件
- asp.net-mvc - 如何在 mvc 中自动增加 ID
- bash - 每十分钟计算方括号中的 ID 的 Bash 脚本
- unreal-engine4 - 设计没有控制器的虚幻引擎 VR 购物应用