MKim
MKim

Reputation: 25

Using perl to split file in flat text

I have a flat file that are created with offsets e.g. row 1: char 1 - 3 = ID, 4-19 = user name, 20 - 40 = last name, etc...

What's the best way to go about creating a perl script to read this? and is there any way to make it flexible based on different offset groups? Thank you!

Upvotes: 0

Views: 74

Answers (1)

ikegami
ikegami

Reputation: 386706

If the positions/lengths are in terms of Unicode Code Points:

# Use :encoding(UTF-8) on the file handle.

my @fields = unpack('A3 A16 A21', $decoded_line);

If the positions/lengths are in terms of bytes:

use Encode qw( decode );

sub trim_end(_) { $_[0] =~ s/\s+\z//r }

# Use :raw on the file handle.

my @fields =
   map trim_end(decode("UTF-8", $_)),
      unpack('a3 a16 a21', $encoded_line);

In both cases, trailing whitespace is trimmed.

Upvotes: 1

Related Questions