Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Raku have a similar function to Python's Struct?

Tags:

raku

Unpacking binary data in Python:

import struct

bytesarray = "01234567".encode('utf-8')
# Return a new Struct object which writes and reads binary data according to the format string. 
s = struct.Struct('=BI3s')
s = s.unpack(bytesarray) # Output: (48, 875770417, b'567')

Does Raku have a similar function to Python's Struct? How can I unpack binary data according to a format string in Raku?

like image 505
ohmycloudy Avatar asked Oct 30 '20 07:10

ohmycloudy


People also ask

How to untangle multiple return values in raku?

Destructuring can be used to untangle multiple return values. Raku has many ways to specify a function's return type: Attempting to return values of another type will cause a compilation error. returns and of are equivalent, and both take only a Type since they are declaring a trait of the Callable.

What is the difference between a class and a struct in Python?

See PEP 557. Backported to Python 3.6 using the dataclasses package. Show activity on this post. Please realise that in C++, the only difference between a class and a struct is that the elements of a class are by default private, as is the inheritance. The following are equivalent: class D : public B { public: ... }; struct D { ... };

How to define a structure in Python?

We all know about the structures used in C and C++. The one that allows to bundle multiple primitive data types into user defined data type. In python, can define a structure using a class, where the user does not define any functions in the class. Ok, I know that even though C doesn’t, C++ allows function definitions in structure.

What is the use of Python struct?

Python struct module is capable of performing the conversions between the Python values and C structs, which are represented as Python Strings. Python struct module can be used in handling binary data stored in files, database or from network connections etc.


1 Answers

There's the experimental unpack

use experimental :pack;

my $bytearray = "01234567".encode('utf-8');

say $bytearray.unpack("A1 L H"); 

It's not exactly the same, though; this outputs "(0 875770417 35)". You can tweak your way through it a bit, maybe.

There's also an implementation of Perl's pack / unpack in P5pack

like image 102
jjmerelo Avatar answered Oct 29 '22 02:10

jjmerelo