I have an array that stores lat/long together. For example:
@values[0] = "-0.709999984318709,60.690000003554324"
I am trying to separate this into two arrays, @lat and @long, based on the comma.
How can I do this?
Thanks
I assume you want to keep each latitude and longitude value together, in which case transforming your array into a two-dimensional array would be appropriate:
my @latlong = map { [ split /,/, $_, 2 ] } @values
I used the full notation of split here in order to invoke the LIMIT condition of 2 fields. It may not matter for this data, but it may matter if the conditions change.
The code of the map statement first splits each element of @values into two, puts the resulting list of 2 into an anonymous array [ ... ], which is then inserted into the new array. The resulting array looks like this when printed with Data::Dumper:
$VAR1 = [
[
'-0.709999984318709',
'60.690000003554324'
]
];
First off, it's better to write $values[0] to reference the array element.
The split command will help you here, assuming the comma is consistent:
foreach (@values) {
my @separated = split(',', $_);
push @lat, $separated[0];
push @long, $separated[1];
}
There's a number of ways this can be done, but I've done it in a manner that should show how the arrays are handled.
$name variable are you talking about? You can't just invent new things to put into your question.$name is the name of each map that I have coordinates for. I tried to keep my question simple by only including the relevent part of my code. Is it better form to include all of the code in my script?
split. So tryperldoc -f split.