使用perl分割可能包含空格的行

时间:2010-06-18 07:43:20

标签: regex perl split whitespace

好的,所以我使用perl来读取包含一些常规配置数据的文件。这些数据根据它们的含义组织成标题。一个例子如下:

[vars]

# This is how we define a variable!
$var = 10;
$str = "Hello thar!";


# This section contains flags which can be used to modify module behavior
# All modules read this file and if they understand any of the flags, use them
[flags] 
  Verbose =       true; # Notice the errant whitespace!

[path]
WinPath = default; # Keyword which loads the standard PATH as defined by the operating system. Append  with additonal values.
LinuxPath = default;

目标:使用第一行作为示例“$ var = 10;”,我想在perl中使用split函数来创建一个包含字符“$ var”和“10”作为元素的数组。以另一行为例:

    Verbose    =         true;
    # Should become [Verbose, true] aka no whitespace is present

这是必需的,因为我将这些值输出到一个新文件(一个不同的C ++代码将读取)来实例化字典对象。只是为了让你对它的外观有所了解(只是随着时间的推移而做好准备):

define new dictionary
name: [flags]
# Start defining keys => values
new key name: Verbose
new value val: 10 
# End dictionary

哦,这是我目前的代码以及它正在做的事情(错误地):

sub makeref($)
{
    my @line = (split (/=/)); # Produces ["Verbose", "    true"];
}

回答一个问题,为什么我不使用Config :: Simple,我最初不知道我的配置文件是什么样的,只是我想要它做什么。随着我的进展 - 至少对我来说似乎是明智的 - 并使用perl来解析文件。

问题是我有一些C ++代码会在配置文件中加载信息,但由于在C或C ++中解析是:(我决定使用perl。这对我来说也是一个很好的学习练习,因为我是新手事情就是这样,这个perl代码并不是我的应用程序的一部分,它只是让C ++代码更容易读取信息。而且,它更具可读性(配置文件和生成的文件)感谢您的反馈,这确实有所帮助。

5 个答案:

答案 0 :(得分:6)

如果您将此解析作为学习练习,那很好。但是,CPAN有几个模块可以为您完成大量工作。

use Config::Simple;
Config::Simple->import_from( 'some_config_file.txt', \my %conf );

答案 1 :(得分:3)

split拆分正则表达式,因此您只需将=符号周围的空白放入其正则表达式中即可:

split (/\s*=\s*/, $line);

你显然不想删除所有空格,否则会生成这样的行(字符串中缺少空格):

$str="Hellothere!";

我想只有从行的开头和结尾删除空格就足够了:

$line =~ s/^\s*(.*?)\s*$/$1/;

一个更简单的替代方案,有两个陈述:

$line =~ s/^\s+//;
$line =~ s/\s+$//;

答案 2 :(得分:2)

好像你已经得到了它。在拆分之前剥去空格。

sub makeref($)
{
    s/\s+//g;
    my @line = (split(/=/)); # gets ["verbose", "true"]
}

答案 3 :(得分:1)

此代码可以解决问题(并且在没有反转的情况下效率更高)。

for (@line) {
    s/^\s+//;
    s/\s+$//;
}

答案 4 :(得分:0)

你可能已经弄明白了,但我想我会补充一点。如果你

sub makeref($)
{
   my @line = (split(/=/));
   foreach (@line)
   {
      s/^\s+//g;
      s/\s+$//g;
   }
}

然后您将删除左侧和右侧之前和之后的空白。那样的话:

 this is a parameter         =      all sorts of stuff here

不会有疯狂的空间。

!!警告:我可能不知道我在说什么!!