whatahitson
whatahitson

Reputation: 365

How to split array values into to separate arrays in perl

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

Upvotes: 3

Views: 18601

Answers (2)

TLP
TLP

Reputation: 67900

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'
          ]
        ];

Upvotes: 6

RichM
RichM

Reputation: 272

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.

Upvotes: 4

Related Questions