简体   繁体   中英

How do I use Perl's unpack?

I have an JSON Body of an http post that has to be split into 80 character double quoted strings - but - whenever I use unpack to read the first 80 characters, the string pointer in the source string (which is not CR/LF delimited at the end of each line yet) never changes - eg the loop below keeps reading the same string over and over - I'm assuming that unpack is expecting a CR/LF to be pre-existing? What do I do if it isn't?

@row =unpack 'A80', $body;
foreach $line (@body)
{
    @row =unpack 'A80', $body;
    print '"'.$line.'"' ;
}

It's really hard to understand your circumstance, but from your own "answer" it looks like you need this

my @groups = unpack '(a80)*', $body;

From your question it looks like this may be better

my @groups = unpack '(A80)*', $body;

But you really need to describe where $body came from, and what results you expect

Here's how I solved the problem:

my $n = 80;    # $n is group size.
my @groups = unpack "a$n" x (length( $body ) /$n ), $body;

# print @groups;
foreach $line (@groups) {
    print '"'.$line.'"' ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM