【问题标题】:read values and path of files from a config file in perl从 perl 中的配置文件读取文件的值和路径
【发布时间】:2014-01-26 02:21:52
【问题描述】:

读取如下配置文件,我可以通过使用数组(通过使用拆分和连接函数)存储“信息”的值,并且能够检查每个数组值的总值,但是我在阅读每个信息值下的文件。

[abc]
Info=alerts,requestes
[alerts]
total=23
/home/value/date/readme.txt
/root/File1
/home/File2
/users/cord/File3
[requestes]
Total=87
C:\user\user1\file1
C:\user\user1\file2
C:\user\user1\file3

你对此有什么想法吗?我们如何通过使用 perl 来实现这一点。 我的预期输出是这样的 警报文件 /home/value/date/readme.txt /root/文件1 /home/文件2 /用户/线/文件3 请求文件 C:\用户\用户1\文件1 C:\用户\用户1\文件2 C:\user\user1\file3

【问题讨论】:

  • 你的预期输出是什么?
  • 输出应该是这样的 警报文件 /home/value/date/readme.txt /root/File1 /home/File2 /users/cord/File3 请求文件 C:\user\user1\文件1 C:\user\user1\file2 C:\user\user1\file3
  • 它寻找参数和值,在我的情况下,没有参数只有值......

标签: arrays perl


【解决方案1】:

我认为您不需要 CPAN 的模块来执行此操作,但它可能会有所帮助。我写了一些代码,希望能帮助你开始。

有很多方法可以做到这一点,但一种方法是读取文件,并将其解析为哈希,同时使用正则表达式来确定哪一行包含哪些数据或内容。

#!/bin/perl
use strict;
use warnings;


my $file = <<'EOD';
[abc]
Info=alerts,requests
[alerts]
total=23
/home/value/date/readme.txt
/root/File1
/home/File2
/users/cord/File3
[requests]
Total=87
C:\user\user1\file1
C:\user\user1\file2
C:\user\user1\file3
EOD

my %info_hash;

my @file_contents = split('\n', $file);


my $title = shift @file_contents;
$title =~ s/\[(.*)\]/$1/g;

print "Title: $title\n";
my $info_string = shift @file_contents;
$info_string =~ s/^.*?=//;
my @info = split(',', $info_string);

my $key;

for my $line (@file_contents) {

    chomp $line;
    if ( $line =~ /^\[(.*?)\]/ ) {
        $key = $1;
    } elsif ( $line =~ /^total=(.*)/i ){
        $info_hash{$key}{total} = $1;
    } else {
        push @{$info_hash{$key}{values}}, $line;
    }
}

for my $entry (keys %info_hash) {
    print "Total for $entry is " . $info_hash{$entry}{total} . "\n";
    print join(" ", @{$info_hash{$entry}{values}}) . "\n";
}

这个程序将它解析成一个哈希值。结构如下:

%info_hash =
'alerts' =>
{
      'values' => [
                    '/home/value/date/readme.txt',
                    '/root/File1',
                    '/home/File2',
                    '/users/cord/File3'
                  ],
      'total' => '23'
};
'requests' =>
{
      'values' => [
                    'C:\\user\\user1\\file1',
                    'C:\\user\\user1\\file2',
                    'C:\\user\\user1\\file3'
                  ],
      'total' => '87'
};

如果您对代码的工作方式有任何疑问,请告诉我。它可能不是您想要的,但它是一个关于如何存储数据的示例的起点。

【讨论】:

  • 谢谢,在这里我无法获得文件的数量,即 Values 的值我怎么能得到那个..
  • 对于总数使用$info_hash{$entry}{total},对于存储所有文件名的数组使用@{$info_hash{$entry}{values}}。查看打印它们的最后一个 for 循环,以获取如何获取它们的示例。希望这会有所帮助!
  • 这段代码足够复杂,需要在 CPAN 上寻找更受支持的版本
猜你喜欢
  • 1970-01-01
  • 2017-07-07
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2021-06-25
  • 1970-01-01
  • 2014-03-03
相关资源
最近更新 更多