0

I have N number of floats in each line of the input text file. I'm trying to convert them into binary format (sequence of four-byte floats).

Sample line from input: -12.391 -5.301 -12.854 0.438 8.499 4.862 -2.481 3.962

I'm using the Perl pack function as below

foreach my $line (@inputData) {
    print $outFileHandle pack('fxfxfxfx... N times', $line);
}

Instead of writing fx N times, what can I do?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user13107
  • 3,239
  • 4
  • 34
  • 54
  • 2
    I think it's a job for the repetition operator (`x`): `… pack( 'fx' x $n, $line ) …` – larsen Apr 12 '13 at 10:08
  • @larsen, thanks but that gives me this error `Argument "-10.309 0.337 -17.267 6.611 6.937 5.338 -0.870 ..." isn't numeric in pack` – user13107 Apr 12 '13 at 10:31
  • Is the x is really needed in pack template (`fx`)? It just adds an extra null byte. It will return an error for sure, You need to split the line to real numbers, as dan1111 suggested. – TrueY Apr 12 '13 at 12:12

1 Answers1

4

pack takes a list of values, while you are trying to give it multiple values within a single variable. Split on whitespace first.

Then you can use the * modifier to accept any number of floats:

pack "f*", split(' ',$line);
  • 2
    If the N is known the pack template can be `f`. This is not clear if this is ta case. But You solution is correct in any case. – TrueY Apr 12 '13 at 12:10