【问题标题】:i want to edit the specific block of data from a file specified through perl script我想编辑通过 perl 脚本指定的文件中的特定数据块
【发布时间】:2013-07-15 10:31:51
【问题描述】:

文件数据块的格式与以下文件相同

edit_file content{
       val0      data0
       val0      data0
       val0      data0
       val0      data0
       val0      data0
   }

我的代码是

my $temp_hash;
open FD, "<temp.cfg";
@array = <FD>;
foreach $line (@array) {
    if ($line =~ /\s+(.*?)\s+(.*)/) {
        foreach $key (keys %tem) {
            $temp_hash{$1} = $2;
        }
    }
    print $temp_hash;
}
foreach $array (keys $1) {
    print "$key is $temp_hash{$key}\n";
}

【问题讨论】:

  • 问题是什么?什么不工作?你期待什么结果?具体点!
  • %tem 来自哪里?那个数据文件到底是什么? - CPAN 上可能已经有一些东西可以解析这些文件
  • 数据文件是上面给定格式的配置文件,%tem 是我声明的临时哈希,如果你发现给定的代码是错误的,你能帮我看看代码

标签: perl file-io


【解决方案1】:

如果您只想解析您的文件到哈希中:

my %data;
open my $fh, "<", "temp.cfg" or die $!;
while ( my $line = readline($fh) ) {

    if ( $line =~ m{^\s+(\S+)\s+(\S+)$} ) {

        $data{$1} = $2;
    }
}
close $fh;

foreach my $key (keys %data) {
    print "$key is $data{$key}\n";
}

【讨论】:

  • 文件中包含几个这样的块,所以如何识别单个/特定的数据块
猜你喜欢
  • 1970-01-01
  • 2020-09-14
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
相关资源
最近更新 更多