如何在Perl中读取定长记录? [英] How do I read fixed-length records in Perl?

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

问题描述

在Perl中读取固定长度记录的最佳方法是什么.我知道要读取以下文件:

What's the best way to read a fixed length record in Perl. I know to read a file like:

ABCDE 302
DEFGC 876

我能做

while (<FILE>) {
   $key = substr($_, 0, 5);
   $value = substr($_, 7, 3);
}

但是没有办法通过读取/解压缩来做到这一点吗?

but isn't there a way to do this with read/unpack?

推荐答案

更新:有关确定的答案,请参见下面的乔纳森·莱弗勒(Jonathan Leffler)的答案.

Update: For the definitive answer, see Jonathan Leffler's answer below.

我不会仅将其用于两个字段(我会使用 pack /解压缩直接),但对于20或50左右的字段,我喜欢使用 Parse :: FixedLength (但我有偏见).例如. (以您的示例为例)(更新:此外,您还可以使用$/和<>代替read($ fh,$ buf,$ buf_length)...请参见下文):

I wouldn't use this for just two fields (I'd use pack/unpack directly), but for 20 or 50 or so fields I like to use Parse::FixedLength (but I'm biased). E.g. (for your example) (Update: also, you can use $/ and <> as an alternative to read($fh, $buf, $buf_length)...see below):

use Parse::FixedLength;

my $pfl = Parse::FixedLength->new([qw(
  key:5
  blank:1
  value:3
)]);
# Assuming trailing newline
# (or add newline to format above and remove "+ 1" below)
my $data_length = $pfl->length() + 1;

{
  local $/ = \$data_length;
  while(<FILE>) {
    my $data = $pfl->parse($_);
    print "$data->{key}:$data->{value}\n";
    # or
    print $data->key(), ":", $data->value(), "\n";
  }
}

有些类似的模块使打包/拆包更加友好"(请参阅​​Parse :: FixedLength的另请参阅"部分).

There are some similar modules that make pack/unpack more "friendly" (See the "See Also" section of Parse::FixedLength).

更新:哇,这是一个替代性的答案,而不是正式的答案...好吧,既然如此,我应该包括乔纳森·莱弗勒的一些更直接的代码,这很可能是您应该怎么做的通常会这样做(请参见 pack /

Update: Wow, this was meant to be an alternative answer, not the official answer...well, since it is what it is, I should include some of Jonathan Leffler's more straight forward code, which is likely how you should usually do it (see pack/unpack docs and Jonathan Leffler's node below):

$_ = "ABCDE 302";
my($key, $blank, $value) = unpack "A5A1A3";

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

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