gpt4 book ai didi

regex - 使用 perl 拆分可能包含空格的行

转载 作者:行者123 更新时间:2023-12-04 01:01:20 25 4
gpt4 key购买 nike

好的,所以我正在使用 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 dictionaryname: [flags]# Start defining keys => valuesnew key name: Verbosenew value val: 10 # End dictionary

Oh, and here is the code I currently have along with what it is doing (incorrectly):

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

要回答一个问题,我为什么不使用 Config::Simple,是因为我最初不知道我的配置文件会是什么样子,只知道我想要它做什么。在我进行的过程中进行弥补 - 至少对我来说似乎是明智的 - 并使用 perl 来解析文件。

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

最佳答案

如果您将此解析作为学习练习进行,那很好。但是,CPAN有几个模块可以为你做很多工作。

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

关于regex - 使用 perl 拆分可能包含空格的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3067913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com