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

Dear Monks,

 my $var ='[1,2]';

In the above line an array reference is stored as a string. I need to convert that string into actual array reference. Please give any suggestions..

Replies are listed 'Best First'.
Re: Converting a String to Array Reference
by moritz (Cardinal) on Jun 29, 2009 at 08:43 UTC
    eval can help you, but is a security risk if it's not actually just an array reference. There's also a CPAN module which parses such strings safely, but I can't remember the name right now. Search the CPAN might help you.
Re: Converting a String to Array Reference
by mscharrer (Hermit) on Jun 29, 2009 at 09:24 UTC
    In this specific case you could do it like this:
    my $var ='[1,2]'; my @array = map { 0+$_ } split ',', substr($var,1,-1);
    If the array holds non-numbers (or you don't care that the numbers are saved as strings) you can remove the 'map { ... }' part.

    However the CPAN module mentioned in earlier post would do this more safely and support more features.

Re: Converting a String to Array Reference
by Anonymous Monk on Jun 29, 2009 at 08:48 UTC
Re: Converting a String to Array Reference
by Marshall (Canon) on Jun 29, 2009 at 17:49 UTC
    This looks a bit strange for an internal variable. I would guess that something like this would come from the outside via a file, etc. Maybe a config file? If that's true, then there are better config modules and syntax for this.

    But anyway, if this is what you have, then I would parse it in the easiest way possible - this is one line.

    #!/usr/bin/perl -w use strict; my $var ='[1,2]'; my @var = split (/[\[\],]/, $var); print "@var";
    This says to split the line based upon the character set of [ ] ,. The required \ escape characters confuse this a bit, but that's all there is to it. to use array ref to this just push \@var on some list...
Re: Converting a String to Array Reference
by doug (Pilgrim) on Jun 29, 2009 at 17:01 UTC

    Just out of curiosity, what itch are you trying to scratch? Is there a way we could avoid doing this? With some more facts, we might be able to side step this issue completely.

    - doug