nasa has asked for the wisdom of the Perl Monks concerning the following question:

I have an array like
@boxed = ("1051","Bucket Man","yui87y","christmas","machine");
if I withdraw an element like so
print ("The second element is $boxed[1]"); All is fine and Bucket Man appears.
Then if I send the array to a data file thus.
$data_path = "saved.data"; $now = time(); open(O, ">$data_path"); print O "@boxed"; close(O);

Then retrieve it.
$data_file="saved.data"; open(DAT, $data_file) || die("Could not open file!"); @raw_data=<DAT>; close(DAT);

print ("The second element inside array raw_data is $raw_data[1]");

Now Bucket man refuses to appear.
Its like by saving to data file and bringing back I have
destroyed the @array format or something.
How can I get Bucket Man back to work.?
I really have spent some time looking for the answer, but relative FAQ`s Tend towards internet entwined network entangled complicated code.
I just simply need Bucket Man back on the job.
God bless Ya all.

Replies are listed 'Best First'.
Re: Annoying array.
by Zaxo (Archbishop) on Apr 25, 2003 at 00:48 UTC

    In print O "@boxed"; , the elements of @boxed are printed seperated by $". By default, that is a space, so all the elements of @boxed are printed on a single line of the output file.

    In @raw_data=<DAT>; , the record seperator is $/ which is the system line end by default. You will find 'Bucket Man' in $raw_data[0], along with all the rest.

    See perlvar for information on $", $/, $\, $, , and friends.

    (Added) You can do what you want by replacing print O "@boxed"; with

    { local $, = $/; print O @boxed; }

    After Compline,
    Zaxo

Re: Annoying array.
by The Mad Hatter (Priest) on Apr 25, 2003 at 00:47 UTC
    You are printing the array on one line in the file with all the elements concatenated together. When you slurp the file back into the array, each line is put in an element of the array. Since there is only one line, only $raw_data[0] exists. If you print that you'll see what I mean.

    When you save to the file, print a newline after each array element (hint, use the join function). When you slurp it back in, the array will be the same, except now each element has a newline appended to it. To get rid of this, read up on chomp.

    Hope this helps.

Re: Annoying array.
by jasonk (Parson) on Apr 25, 2003 at 00:48 UTC

    Take a look at the contents of the file and you'll see that you are saving all the array elements on one line, so when you retrieve it everything is in $raw_data[0]. To save them to individual lines, change print O "@boxed"; to print O join("\n",@boxed),"\n";


    We're not surrounded, we're in a target-rich environment!
      Well, if you do that, you should chomp after reading in the data, and just pray your original data does not contain a newline.

      The OP wants to serialize data. There are several modules doing that: Serialize, Data::Dumper and YAML.

      Abigail