3 ms·
Demystifying pack and unpack, these most misunderstood functions
- richard_todd 4y agoPack is great, but one feature I always wish for is to pack into the middle of an existing string. So instead I have to pack into a new string and then copy it into the destination. Python has struct.pack_into for this case. I know the performance difference would be small, and if I really care so much about efficiency I shouldn't write it in a scripting language anyway. It's just one of those things that bugs me.
- mfontani 4y ago$ perl -E'$s = "bar"; substr($s, 1, 1) = pack("A*", 60); say $s' b60r
- richard_todd 4y agoYou have just demonstrated copying the result of the call to pack() into a string. That's what I already do, but what I want is a version that just writes over bytes in $s without creating the "60" string.
- jefftk 4y agoPython equivalent: https://docs.python.org/3/library/struct.html https://docs.python.org/3/library/struct.html
- emmelaich 4y agoThis documentation is a model of clarity.
- jandrese 4y agoI really appreciate this. pack and unpack are the two functions that give me the most trouble in perl by far. They look so simple but the implementation details are killer.
- znpy 4y agomany years ago while playing with CGI (CGI::Simple? can't remember now) i saw a line that parsed the query string by means of unpack... It was short and terse, it felt like black magic.
- andrewshadura 4y agoWhat exactly is mysterious and misunderstood about pack and unpack? I personally understood it right from the start.
- lupire 4y agoIt's conceptually simple, but like changing bases in math, the notation is confusing and the different numeric/string datatypes are not clearly annotated.
- Isamu 4y agoI used it very extensively and still found myself confused sometimes with complicated situations where I would have to unpack and then pack the results, or vice versa. It’s powerful and terse, you can use it in so many situations to accomplish so much.
- ok123456 4y agoWonder if this was inspired by Fortran's FORMAT strings.
- adrianmonk 4y agoPerl's format mechanism was: https://perldoc.perl.org/perlform https://perldoc.perl.org/perlform These days it's pretty obsolete since if you want to generate a nicely formatted report, you can just generate HTML.