develooper Front page | perl.beginners | Postings from January 2012

Re: Dereferencing an array

Thread Previous | Thread Next
From:
Rob Dixon
Date:
January 27, 2012 03:12
Subject:
Re: Dereferencing an array
Message ID:
4F22867D.1050809@gmx.com
On 27/01/2012 10:14, Owen wrote:
> In the program below, I think I end up with an array of array
> references.
>
> But I can not get back the @rest from @desc where it is stored.
>
> Is it possible that @rest is just over written? Might have to think
> about doing something else. I can't use hashes as data  elements are
> sometimes duplicated.
>
> Any clues as to the syntax to get back the data would be appreciated
>
> TIA
>
> Owen
>
> ============================================================
> #!/usr/bin/perl
>
> use strict;
> use warnings;
>
> my @lat;
> my @lon;
> my @desc;
> my $rest_ref;
>
> while (<DATA>) {
>      my ( $lat, $lon, @rest ) = split;
>      print "@rest";
>      $rest_ref = \@rest;
>      push( @desc, $rest_ref );
>
> }
>
>
>
> __DATA__
> 36.97972        148.88564       House post
> 36.97853        148.87706       Second fence post
> 36.97847        148.88756       Curve in road
> 36.98050        148.88569       Delegate side of gate
> 36.97694        148.88844       Culvert
> 36.97956        148.88550       Power Pole
> 36.98150        148.88344       Dam
> 36.97922        148.88036       Dam wall
> ============================================================

Hi Owen

Well done on a nicely layed-out program.

You can access the anonymous arrays from @desc using

   foreach my $rest (@desc) {
     print "@$rest\n";
   }

But there is no need to split the thrid field in the first place. You
have two options: first to split on more than a single space with

   my ( $lat, $lon, $rest ) = split /\s{2,}/;

and secondly to limit the number of fields that split() divides the
record into

   my ( $lat, $lon, $rest ) = split ' ', $_, 3;

Be aware that both of these techniques will leave the newline on the end
of the last field, so a call to chomp() will be necessary as the first
line of the while loop.

HTH,

Rob



Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About