in reply to Re: help needed in storing the return values of unpack
in thread help needed in storing the return values of unpack

hai monks,
your answers will work nicely if i have only few templates in the unpack operation.
but if we have 20 templates how can i manage to use your answer.
unpack("U20A10A10A10x10A10A10A10x10A10x10A10A10x10A10A10",$string);
How can i store the return values of this unpack operation in two arrays?.
i mean "U20" in array @first and the remaining in array @second
even "U20" itself returns 20 elements.How can i do that efficiently.

Replies are listed 'Best First'.
Re^3: help needed in storing the return values of unpack
by GrandFather (Saint) on Mar 23, 2006 at 09:40 UTC

    Use splice. It's most likely most efficient. Least prone to errors due to writing out ling lists of elements, and scales to as many elements in each array as you need. Indeed the parameters for splice can be calcualted at run time so you can change the split point to suit whatever is required.


    DWIM is Perl's answer to Gödel
Re^3: help needed in storing the return values of unpack
by Corion (Patriarch) on Mar 23, 2006 at 09:39 UTC

    Any array you give as a parameter will gobble up all remaining items. So the following will work for you I guess:

    my ($first, @rest) = unpack "U20A10A10A10", $string;
      hai Corion,
      Your answer will not work. since U20 will return 20 elements,so the first element will be stored in $first , and remaining 19 elements and the strings returned by A10A10A10 will be stored in the array @second.

        Ooops - I thought that U returned a Unicode string and not single items, so my answer is wrong. You should go with GrandFather's approach and move the 20 items out of the array later:

        my @items = unpack "...", $string; my @first = splice @items, 0, 20;