Perl - 获取第一个“单词"从输入字符串 [英] Perl - get first "word" from input string

查看:126
本文介绍了Perl - 获取第一个“单词"从输入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 Perl 程序,该程序从文本文件中读取行,并且对于每一行,从该行中提取第一个单词",并根据返回的字符串执行不同的操作.

I am trying to write a Perl program that reads in lines from a text file, and, for each line, extract the first "word" from the line, and perform a different action based on the string that gets returned.

主循环如下所示:

while(<AXM60FILE>) {

   $inputline = $_;

   ($start) = ($inputline =~ /\A(.*?) /);

perform something, based on the value of string in $start

}

输入文件其实就是一个参数文件,里面有parameter_name和parameter_value,用冒号(:")隔开.冒号前后可以有空格或制表符.

The input file is actually a parameter file, with the parameter_name and parameter_value, separated by a colon (":"). There can be spaces or tabs before or after the colon.

因此,文件看起来(例如)如下所示:

So, the file looks (for example) like the following:

参数 1:xxxxxxxxxxxx
参数 2 :xxxxxxxxxxxxx
参数 3 : xxxxxxxxxxxxxxxxx
参数 4:xxxxxxxxxxxxx

param1: xxxxxxxxxxxx
param2 :xxxxxxxxxxxxx
param3 : xxxxxxxxxxxxxxxxx
param4:xxxxxxxxxxxxx

那个"($start) = ($inputline =~/\A(.*?)/);"适用于param2"示例和param3"示例,其中第一个单词以空格/空格结尾,但是我如何处理param1"和param4"情况,其中 parameter_name 后面紧跟冒号?

That "($start) = ($inputline =~ /\A(.*?) /);" works ok for the "param2" example and the "param3" example where the 1st word is terminated by a blank/space, but how can I handle the "param1" and "param4" situations, where the parameter_name is followed immediately by the colon?

另外,如果空白"是一个或多个制表符,而不是空白/空格字符呢?

Also, what about if the "whitespace" is a tab or tabs, instead of blank/space character?

谢谢,吉姆

推荐答案

这将涵盖您的所有案例,然后是一些:

This will cover all of your cases and then some:

my ($key, $value) = split /\s*:\s*/, $inputline, 2;

(或者,在英语中,将 $inputline 拆分为最多两个元素,由任意数量的空格、冒号和任意数量的空格分隔.)

(Or, in English, split $inputline into a maximum of two elements separated by any amount of whitespace, a colon and any amount of whitespace.)

这篇关于Perl - 获取第一个“单词"从输入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆