http://www.perlmonks.org?node_id=987794

BrowserUk has asked for the wisdom of the Perl Monks concerning the following question:

In a recent post I described a method I discovered for packing hashes and arrays. As part of the description, I typed a few examples into my REPL and pasted the output in the post; 10 lines of sample code being worth a 1000 words of verbiage.

But I just realised that I made a typo. Instead of using a template of n/(n/a*)*, I accidentally omitted the final *. But the mystery is, it still worked:

$packed = pack 'n/(n/a*)', 1..10;; @array = unpack 'n/(n/a*)', $packed;; print @array;; 1 2 3 4 5 6 7 8 9 10

The question is why? Why did pack see fit to pack all 10 values rather than just the first?

Is there a logical explanation, or are the last 3 digits of the id of the above linked node somehow responsible :)


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

The start of some sanity?

Replies are listed 'Best First'.
Re: Mystery! Logical explanation or just Satan's work?
by SuicideJunkie (Vicar) on Aug 16, 2012 at 15:23 UTC
    $packed = pack 'n/(n/a*)', 1..9;; @array = unpack 'C*', $packed;; print join ', ' , @array;;
    Gives: 0, 9, 0, 1, 49, 0, 1, 50, 0, 1, 51, 0, 1, 52, 0, 1, 53, 0, 1, 54, 0, 1, 55, 0, 1, 56, 0, 1, 57

    It looks to me like the first n/ is storing the size of your list. The (n/a*) part is then used that many times (in this case, 9).

      You're right! I was misinterpreting the prefixed count. That's both good and bad news.

      1. Good news: It works!

        As in it packs/unpacks a list of data reliably.

      2. Bad news: Its not so good for length/data transmission protocols.

        Which want the prefix to be a count of the bytes in the packet; not the number of fields.

        That means an extra step is required:

        $p = pack 'N/a*', pack '(n/a*)*', 1..10, 'aaaa'..'aaaz';; %h = unpack '(n/a*)*', unpack 'N/a*', $p;; pp \%h;; { 1 => 2, 3 => 4, 5 => 6, 7 => 8, 9 => 10, aaaa => "aaab", aaac => "aaad", aaae => "aaaf", aaag => "aaah", aaai => "aaaj", aaak => "aaal", aaam => "aaan", aaao => "aaap", aaaq => "aaar", aaas => "aaat", aaau => "aaav", aaaw => "aaax", aaay => "aaaz", }

        That's cool, but important to know.


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

      The start of some sanity?