In perl, with an array that only has integers and doubles like @array = qw/4 3.1416 6.7 15 4.3/, how do you pack the list into a sequence of binaries and save it to a .bi file, where the binary has to be exactly an int when an element is an integer and double when the element is double. This format is essential because I need to feed itto an external executable.
Asked
Active
Viewed 154 times
1 Answers
4
for (@array) {
if (int($_) == $_) {
$output .= pack($int_format, $_);
} else {
$output .= pack($double_format, $_);
}
}
That said, there's no way the file format you specify could be read by anything. The reader needs to know whether the next thing to read is stored as an integer or as a double, but that information is not available to it.
Maybe you meant you wanted to select the format based on the presence or absence of .
in the strings in @array
. In that case, you'd use the following:
for (@array) {
if (/\./) {
$output .= pack($double_format, $_);
} else {
$output .= pack($int_format, $_);
}
}
You've since mentioned the reader expects a specific pattern of floating point numbers and integers. So why not just use that same pattern?
$output .= pack("$int_format$double_format$double_format$int_format$double_format", @array);
Note that I left the exact format vague. That's because you did as well.
- You didn't specify the size of the integer:
- 8-bit integer (
c
) - 16-bit integer (
s
) - 32-bit integer (
l
) - 64-bit integer (
q
or use Math::Int64) - Same as the
int
of the compiler that compiled Perl (i
) - Same as Perl uses (
j
)
- 8-bit integer (
- The format for double-precision floating point numbers is
d
. - You didn't specify endianness (for either the integer and the floating-point number):
- little-endian (append
<
) - big-endian (append
>
) - native endianness (no suffix)
- little-endian (append

ikegami
- 367,544
- 15
- 269
- 518
-
1Perhaps you should stop to think before replying. I repeat: The first snippet produces unusable output. Period. Consider what happens for `@array = qw/4.0 .../` vs `@array = qw/4.1 .../` – ikegami Aug 02 '17 at 16:20
-
I am sorry, I am probably misunderstanding something, but your first suggestion worked well.. – Aki Aug 02 '17 at 17:36
-
You obviously didn't run the test I mentioned. I can't keep you from lying to yourself, but it's your program that's going to break and your reputation on the line, not mine. – ikegami Aug 02 '17 at 17:37
-
I see now, it is working because the double values I get are so unlikely to hit exactly an integer but at one point it would hit one and give a wrong binary file like you pointed out. – Aki Aug 03 '17 at 13:34