# Perl: Is it possible to convert a string to an array reference?



## andynic (May 25, 2007)

Hi,
The snippet of code along with its output below is a simplificationn of something I am trying to do via html tags in perl CGI. The end-result is the same.

My question is this: considering the variable $str near the end of the snippet, is there a way to "re-make" it into a bona fide array reference so that the error message is not produced, and so that it functions as the original $ptrToX.

#!/usr/bin/perl -w
use strict;

my @x = ("apples", "pears", "bannas");
print "x[1] = $x[1]\n"; # displays "pears"

my $ptrToX = \@x;
print "ptrToX->[1] = $ptrToX->[1]\n"; #displays "pears"

print "ptrToX = $ptrToX\n"; #displays the array reference.

open (OUTFILE, ">x.dat") || die "Can't open file for output";
print OUTFILE "$ptrToX\n";
close (OUTFILE);

open (INFILE, "<x.dat") || die "Can't open file for input";
my $str = <INFILE>;
close (INFILE);

print "str = $str\n"; #displays the array ref (but it's really a string here)
print "str->[1] = $str->[1]\n"; #displays error."Can't use string ("ARRAY(...)") as an ARRAY ref while "strict refs" in use at x.pl line 23"

The actual output:
=============
$ perl -w x.pl
x[1] = pears
ptrToX->[1] = pears
ptrToX = ARRAY(0x10082ade8)
str = ARRAY(0x10082ade8)

Can't use string ("ARRAY(0x10082ade8)") as an ARRAY ref while "strict refs" in use at x.pl line 24.

Thanks for your help.
Andynic


----------

