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.
3 Answers
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 );
2 Comments
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
split, but eval is a dangerous sledgehammer that is rarely appropriate.substr($string, 1, -1) needs a comment, and good code should be able to stand on its own without comments.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]