简体   繁体   中英

Get the number of elements for a Perl pack/unpack template

Given a template string for the pack or unpack function, is there a simple way to determine the minimum number of additional arguments expected by pack , and/or the minimum number of values that would be returned by a successful unpack ?

For example:

unpack_element_count("vVC16a16") => 19 # a16 gives one string
pack_element_count("(VVVvx4)2")  => 8  # x4 ignored, 4*2
pack_element_count("v*")         => 0

$count =()= unpack($template, ""); doesn't sound good, since the documentation for unpack says on attempting to unpack a string which is too short, "the result is not well defined". I suppose I could pass a string with an enormous number of zero bytes, but that sounds rather inefficient, and possibly might not be valid for some fancier templates?

If it helps, I'm mainly actually interested in just templates with fixed element counts, meaning no * counts, no / prefix-count-in-data formats, etc. So an answer to this limited case will be helpful; an answer to the more general case (the minimum of a variable count) would be interesting.

There's no builtin tool provided to do this.

I doubt something exists on CPAN, but feel free to search there to see if there's something that can help you. (Module recommendations are off-topic.)

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