perl - 如何使用 Perl 仅解析文件的一部分?

标签 perl

我是 Perl 的新手,但我听说它非常适合解析文件,所以我想试一试。

我有一个包含以下示例信息的文本文件:

High school is used in some
parts of the world, particularly in
Scotland, North America and Oceania to
describe an institution that provides
all or part of secondary education.
The term "high school" originated in
Scotland with the world's oldest being
the Royal High School (Edinburgh) in
1505.

The Royal High School was used as a
model for the first public high school
in the United States, the English High
School founded in Boston,
Massachusetts, in 1821. The precise
stage of schooling provided by a high
school differs from country to
country, and may vary within the same
jurisdiction. In all of New Zealand
and Malaysia along with parts of
Australia and Canada, high school is
synonymous with secondary school, and
encompasses the entire secondary stage
of education.

======================================
Grade1 87.43%
Grade2 84.30%
Grade3 83.00%
=====================================

我想解析文件,只获取数字信息。一世
查看正则表达式,我想我会使用类似的东西
if (m/^%/) {
    do something
}
else {
    skip the line
}

但是,我真正想做的是跟踪变量
left 并将数值存储在该变量中。所以,经过
解析文件,我真的很想拥有以下变量
将 % 值存储在其中。原因是,我想
创建不同等级的饼图/条形图。

Grade1 = 87.43 Grade2 = 84.30



...

你能建议我应该考虑的方法吗?

最佳答案

你需要一个正则表达式。像下面这样的东西应该工作

while (<>) {
  /(Grade[0-9]+)\s*([0-9]+\.[0-9]+)/;
  $op{$1} = $2;
}

作为过滤器。 op hash 将存储成绩名称和分数。这比自动实例化变量更可取。

关于perl - 如何使用 Perl 仅解析文件的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3960914/

相关文章:

Perl 频率排序和其他东西

perl - 如何从 OO Perl 中的子进程读取 STDOUT

perl - 使用 perl 进行 DNA 分析的基本正则表达式和字符串操作

perl - 谁能用 Perl 解释一下(我的 $self = shift)

perl - 未定义 uselongdouble 而在 Perl 构建配置中定义了 d_longdbl 是什么意思?

regex - Perl Regexp::Common 意外匹配错误的 URL

perl - Module::Starter 的 manifest.t 中预期的开发过程是什么?

perl - 给定一个输入词,如何生成发音相似的词列表?

perl - 当数据长度未知时,从 Perl 中的套接字接收数据的最佳方法是什么?

perl - 模板工具包包含钩子(Hook)吗?