neversaint
neversaint

Reputation: 63984

How to unpack a string - created with sprintf - with fixed width in Perl

The following line with fixed with:

my $line = 'ATOM      1  P   CYT B   3      42.564 -34.232  -7.330  1.00105.08           P'

Is created with the following sprintf.

@entr = ( 'ATOM', '1', 'P', 'CYT', 'B', '3', '42.564', '-34.232', '-7.330', '1.00', '105.08', 'P' );
print sprintf("%-6s%5d  %-4s%3s %1s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f          %2s\n",@newentr)

What I want to do is to reverse the process. Namely with $line as input create the array that looks exactly like @entr. How can I achieve that in Perl?

Upvotes: 0

Views: 311

Answers (1)

choroba
choroba

Reputation: 241758

You can use unpack, or alternatively, a regex:

#                    %-6s%5d  %-4s%3s %1s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f          %2s\n
my @rev_eng = unpack 'a6 a5 x2 a4 a3x1 a1 a4 x4 a8   a8   a8   a6   a6   x10       a2', $output;

my $reg = qr/^(.{6}) (.{5}) .. (.{4}) (...) . (.) (.{4}) .{4} (.{8}) (.{8}) (.{8}) (.{6}) (.{6}) .{10} (..)/x;
my @regex = $output =~ $reg;

s/^\s+|\s+$//g for @rev_eng, @regex;

In a template, a stands for string, x ignores the given number of bytes (spaces in this case).

Upvotes: 4

Related Questions