whatahitson has asked for the wisdom of the Perl Monks concerning the following question:

Hi. I have an array, @values containing coordinates. And entire array prints like this:

-0.709999984318709,60.690000003554324 -1.409999984834652,60.710000003710384 -1.389999984788378,60.970000003922536 -0.679999984264137,60.950000003761929 -0.709999984318709,60.690000003554324

but each element is actually a string with both lat and long, separated by a comma. I want to split this into two arrays, one that stores all my longitudes, and another that stores all of my latitudes. How can I do this?

Replies are listed 'Best First'.
Re: Splitting arrays
by choroba (Cardinal) on Jun 04, 2013 at 12:12 UTC
    Use split on each value to get a longitude and latitude.
    #!/usr/bin/perl use warnings; use strict; my @values = qw/1.0,2.2 2.20394,3.02934 34.0293,34.0293/; my (@latitudes, @longitudes); ( $latitudes[@latitudes], $longitudes[@longitudes] ) = split /,/ for @values; print "Longitudes: @longitudes,\nLatitudes: @latitudes.\n";

    Update: Fixed typo.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Splitting arrays
by rjt (Curate) on Jun 04, 2013 at 12:10 UTC

    Please see Markup in the Monastery for help on markup; as far as I can tell from your description, your array actually looks like this:

    my @values = do { no warnings 'qw'; qw/ -0.709999984318709,60.690000003554324 -1.409999984834652,60.710000003710384 -1.389999984788378,60.970000003922536 -0.679999984264137,60.950000003761929 -0.709999984318709,60.690000003554324 / };

    Right? As always, posting your actual code immensely helps us help you. Assuming I'm right, let me point you to two bits of documentation that should render the solution rather trivial: split and push. In general, you would create two arrays, say, @latitude and @longitude, and for each entry in @values, split it on the comma, and push the resulting values to their respective arrays. foreach will be of additional help if you are not yet familiar with Perl looping constructs.

    Edit: Threw in no warnings 'qw'; in artificial scope to squelch "Possible attempt to separate words with commas" when running with warnings, as you should do.

Re: Splitting arrays
by BillKSmith (Monsignor) on Jun 04, 2013 at 13:43 UTC
    It is probably a bad idea to split such closely related data into separate arrays. Use a hash of arrays.
    my %location_data; foreach (@values) { my @vals = split /,/, $_; push @{$location_data{lat}}, $val[0]; push @{$location_data{lon}}, $val[1]; }

    Depending on how you use the data, it may be more convenient to have an array of coordinate pairs. (Like you already have except each pair would be stored as a two element numeric array rather than as a string.

    my @locations = [map {split /,/, $_]} @values;
    Bill
Re: Splitting arrays
by jnyman (Acolyte) on Jun 04, 2013 at 12:24 UTC
    Suggestion:
    my $val_str = join "\n" => @values; my @latitudes = $val_str =~ /(.*),/g; my @longitudes = $val_str =~ /,(.*)/g;