如何在perl中为匹配模式的键添加值

  • 本文关键字:模式 添加 perl perl
  • 更新时间 :
  • 英文 :


我正在学习perl哈希,我被困在一个点。你能帮我解决这个问题吗?

我正在读取一个文件,并在哈希中存储行号和数据,并在Excel中打印。目前我正在实现哈希变量。我的要求是匹配一行中的一个模式,如果找到匹配,则存储一个字符串。

cat file1
line1 abc line1a .
line2 ddf line2a
line3 dde line3a
....
....
%value={ 1:
line1 abc line1a => "somestring"
2: 
line2 ddf line2a => ""
...}

我现在使用代码

use strict;
use warnings;
use feature "say";
use Data Dumper;
my $No=1;
my %value;
open(INPUT,"file1");
while (<INPUT>) {
$value{$No}{$_}="";
$No=$No+1;
}
close <INPUT>

你能在这里提些建议吗?另外,我的文件中有超过150行。

除外

------------------------------------- -----------------------
|         Question                   |         Answer       |
------------------------------------- -----------------------
| How many Teams are present         |    10                |
------------------------------------- ----------------------
| Total no of participate joined     |     234              |
------------------------------------- -----------------------
| No of player`s name Start with L   |                      |
------------------------------------- -----------------------
| Total No of MoM won by Team        |     Team F           |
------------------------------------- -----------------------

我正在使用EXCEL::Writer::XLSX模块创建XLS格式。仍然没有实现,因为我被困在收集数据

我正在努力更好地理解这个问题。

你想创建一个哈希值

  • 键为行号和数据
  • 值是"somestring"如果模式匹配并且"如果不是。

我会根据这个理解来回答。如果有帮助,请告诉我。

假设-输入是一个常规文件。

哈希包含一个键和与之关联的值。例如:%value = ('A' =>abc, 'B' =>def, 'C' =>ghi);

获取以下内容:

%值= {1:line1a =>"somestring"2:Line2 =>"…}

你可以尝试这样做:

use strict;
use warnings;
use Data:Dumper;
my $pattern = "abc"; //desired pattern
my $line_no = 1;
my %data;
//Opening the file in read mode
open(INPUT, "<", "file1") or die "Cannot open file :$!n";
//Parsing the File till the end of file
while(<INPUT>){
chomp($_);
my key  = join(":", $line_no, $_); //Use any delimiter to join these. I have used ":" here. You can use " " to add space as delimiter.
//Check for the pattern and store "something" as the value for the matching hash line
if($_ =~ /$pattern/){
$data{$key} = "something";
} else {
$data{$key} = "";
}
$line_no++;
}
close INPUT;
print Dumper (%data);

输出:

$VAR1 = {

'1: ABC line 1a' = "something",

'2: DDF line 2a' = ",

等等

}

最新更新