in reply to Reading into array with sscanf

The correct answer is to choose an appropriate data format to save as, such as CSV, JSON, XML, etc. You can then use your module of choice for reliably reading and writing. If it's just for temporary backing storage then Storable, Sereal and friends will do the job too.

However, for your example set of integers here's a workable approach using split:

#!/usr/bin/env perl use strict; use warnings; my $save_fn = 'colintu.dat'; my @c_speed = (5, 8, 12, 8); open my $sfh, '>', $save_fn or die "Unable to open file $save_fn : $!"; print $sfh "@c_speed\n"; close $sfh; open my $lfh, '<', $save_fn or die "Unable to open file $save_fn : $!"; @c_speed = split / /, <$lfh>; print "Have: @c_speed\n"; close $lfh; unlink $save_fn; # clean up

(Edited for typo fix - thanks, Corion)


🦛

Replies are listed 'Best First'.
Re^2: Reading into array with sscanf
by colintu (Acolyte) on Jul 16, 2024 at 11:38 UTC
    Ah, thanks, that is what I was looking for (or failing to remember). I don't want to use any of the usual things like JSON, XML etc because this has got to be extremely light weight as it's going to be embedded.

      I don't want to use any of the usual things like JSON, XML etc because this has got to be extremely light weight as it's going to be embedded

      That's fine. I still encourage you to structure your lightweight script file into (unit-testable) subroutines at the top of the file, with each subroutine having well-defined inputs and outputs and not relying on global data ... followed by a short mainline at the end.

      A simple example of this approach can be found in this node.

      👁️🍾👍🦟
Re^2: Reading into array with sscanf
by colintu (Acolyte) on Jul 16, 2024 at 13:08 UTC
    I tried your example and it works BUT it does not do the same as my code example. My code fragments return values into the c_speed array that are *numeric* not the strings that split returns, Which is why I was using sscanf from String::Scanf The variable array c_speed needs to be numeric not string because the values get processed elsewhere.

      Perl makes very little difference between strings and numbers.

      There are Perl operators, like + that treat their arguments as numbers, and other operators that treat their arguments as strings.

      Where in your code do you see that the variables get treated differently?

      They perform just fine in a numeric context.

      #!/usr/bin/env perl use strict; use warnings; my $save_fn = 'colintu.dat'; my @c_speed = (5, 8, 12, 8); open my $sfh, '>', $save_fn or die "Unable to open file $save_fn : $!"; print $sfh "@c_speed\n"; close $sfh; open my $lfh, '<', $save_fn or die "Unable to open file $save_fn : $!"; @c_speed = split / /, <$lfh>; print "Have: @c_speed\n"; @c_speed = map { $_ * 2 } @c_speed; print "Doubled: @c_speed\n"; close $lfh; unlink $save_fn; # clean up

      🦛