0

Say, there is a string "[1,2,3,4,5]", how could I change it to an array reference as [1,2,3,4,5]? Using split and recomposing the array is one way, but it looks like there should be a simpler way.

0

3 Answers 3

5

eval is the simplest way

$string = "[1,2,3,4,5]";
$ref = eval $string;

but this is insecure if you don't have control over the contents of $string.

Your input string is also valid JSON, though, so you could say

use JSON;
$ref = decode_json( $string );
Sign up to request clarification or add additional context in comments.

2 Comments

How could I forget eval? Thanks a lot. I'll do a double check after 'eval' to ensure it's a 'ARRAY' reference.
@Yang You might want to do a double check before eval. :)
3

You can use eval but this should definitely be avoided when the string in question comes from untrusted sources.

Otherwise you have to parse it yourself:

my @arr = split(/\s*,\s*/, substr($string, 1, -1));
my $ref = \@arr;

4 Comments

I try to avoid using 'split', but the one is nice. Thanks.
@Yang: You have your priorities backwards. There is no reason to avoid using split, but eval is a dangerous sledgehammer that is rarely appropriate.
This is the right approach, but relies on the string being exactly as the OP shows, with no whitespace anywhere. The data may indeed be as tightly formatted as that, but if it is then there are much nicer ways of finding the values of the contained fields. An expression like substr($string, 1, -1) needs a comment, and good code should be able to stand on its own without comments.
@Borodin I modified the example to be slightly more forgiving about whitespace. I don’t know the exact requirements so I can’t do much more. Thanks for the comment, though.
2

You really should avoid eval if you can. If the string comes from outside the program then untold damage can be done by simply applying eval to it.

If the contents of the array is just numbers then you can use a regex to extract the information you need.

Here's an example

use strict;
use warnings;

my $string = "[1,2,3,4,5]";
my $data   = [ $string =~ /\d+/g ];

use Data::Dump;
dd $data;

output

[1 .. 5]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.