문제

Is there a way to get number of bytes that "consumed" by an 'unpack' call? I just want to parse(unpack) different structures from a long string in several steps, like following:

my $record1 = unpack "TEMPLATE", substr($long_str, $pos);

# Advance position pointer
$pos += NUMBER_OF_BYTES_CONSUMED_BY_LAST_UNPACK();

# Other codes that might determin what to read in following steps
# ...

# Read again at the new position
my $record2 = unpack "TEMPLATE2", substr($long_str, $pos);
도움이 되었습니까?

해결책

This does seem like a glaring omission in unpack, doesn't it? As a consolation prize, you could use an a* to the end of the unpack template to return the unused portion of the input string.

# The variable-length "w" format is to make the example slightly more interesting.
$x = pack "w*", 126..129;
while(length $x) {
    # unpack one number, keep the rest packed in $x
    ($n, $x) = unpack "wa*", $x;
    print $n;
}

If your packed string is really long, this is not a good idea since it has to make a copy of the "remainder" portion of the string every time you do an unpack.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top