3

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

3
  • Is the array element actually a string with a comma in the middle, or a reference to an array with 2 elements? Commented Jun 4, 2013 at 9:02
  • @WumpusQ.Wumbley its a string with a comma in it. I created it by spliting a string into an array based on spaces. Commented Jun 4, 2013 at 9:05
  • You knew that you wanted to split. So try perldoc -f split. Commented Jun 4, 2013 at 9:20

2 Answers 2

6

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'
          ]
        ];
Sign up to request clarification or add additional context in comments.

Comments

4

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.

4 Comments

thanks. this works but seems to do something odd with my loop print "$name: @values\n\n"; would return each area name and its coordinates, one by one. but print "$name: @long\n\n"; returns all the longitudes for all of the areas, repeatedly for every name. I think I put the code in the right place, but cant think of why this.
@whatahitson What $name variable are you talking about? You can't just invent new things to put into your question.
@TLP $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?
@whatahitson If you want recommendations on a data structure, yes.

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.