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)


🦛


In reply to Re: Reading into array with sscanf by hippo
in thread Reading into array with sscanf by colintu

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.