在 Perl 中读取数据块 [英] Read chunks of data in Perl

查看:69
本文介绍了在 Perl 中读取数据块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当没有我可以使用的分隔符时,在 Perl 中将一行分割成不同长度的部分有什么好方法.我的数据是按列长度组织的,所以第一个变量在位置 1-4,第二个变量在位置 5-15,等等.有很多变量,每个变量都有不同的长度.

What is a good way in Perl to split a line into pieces of varying length, when there is no delimiter I can use. My data is organized by column length, so the first variable is in positions 1-4, the second variable is positions 5-15, etc. There are many variables each with different lengths.

换句话说,有没有办法根据字符串中的位置而不是匹配的表达式来使用split函数?

Put another way, is there some way to use the split function based on the position in the string, not a matched expression?

谢谢.

推荐答案

是的.unpack 函数非常适合处理固定的-宽度记录.

Yes there is. The unpack function is well-suited to dealing with fixed-width records.

my $record = "1234ABCDEFGHIJK";
my @fields = unpack 'A4A11', $record;  # 1st field is 4 chars long, 2nd is 11

print "@fields";                       # Prints '1234 ABCDEFGHIJK'

第一个参数是模板,它告诉 unpack 字段的开始和结束位置.第二个参数告诉它解压哪个字符串.

The first argument is the template, which tells unpack where the fields begin and end. The second argument tells it which string to unpack.

unpack 也可以通过指定空字节 x 来告诉忽略字符串中的字符位置.模板 'A4x2A9' 可用于忽略上述示例中的 AB".

unpack can also be told to ignore character positions in a string by specifying null bytes, x. The template 'A4x2A9' could be used to ignore the "AB" in the example above.

参见 perldoc -f packperldoc perlpacktut 以获得深入的细节和示例.

See perldoc -f pack and perldoc perlpacktut for in-depth details and examples.

这篇关于在 Perl 中读取数据块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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