How to split array values into to separate arrays in perl

16,740

Solution 1

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.

Solution 2

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'
          ]
        ];
Share:
16,740
whatahitson
Author by

whatahitson

Work with GIS, trying to master coding.

Updated on June 04, 2022

Comments

  • whatahitson
    whatahitson almost 2 years

    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