首页 > 解决方案 > 将字符串拆分为哈希

问题描述

我有一些这样的日志消息:

foo=value bar="some other value" complex.key="something more \"complex\""

将这样的字符串拆分为相应的哈希的最简单方法是什么?

在这种情况下,预期的输出将是:

{
  'foo' => 'value',
  'bar' => 'some other value',
  'complex.key' => 'something more "complex"'
}

标签: regexperl

解决方案


这就是Text::ParseWords的用途。

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Text::ParseWords;
use Data::Dumper;

my $in = 'foo=value bar="some other value" complex.key="something more \"complex\""';

my %hash = parse_line('[= ]', 0, $in);

say Dumper \%hash;

输出:

$VAR1 = {
          'complex.key' => 'something more "complex"',
          'foo' => 'value',
          'bar' => 'some other value'
        };

聪明之处都发生在parse_line()。它的三个参数是:

  • 定义输入字符串中字段分隔符的正则表达式(此处为空格或“=”)
  • 指示是否要在字符串周围保留引号的标志
  • 你的输入字符串

推荐阅读