aschepler
aschepler

Reputation: 72401

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.

Upvotes: 1

Views: 97

Answers (1)

ikegami
ikegami

Reputation: 385917

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.)

Upvotes: 1

Related Questions