首页 > 解决方案 > 如何在 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

注意 :: 在这里我无法打印完整的单词,如“小测试”、“大城市”

期望:我需要完整的单词“样本测试”和“大城市”任何人请帮助我

标签: perl

解决方案


处理带引号的字符串的一个不错的模块是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
        };

推荐阅读