develooper Front page | perl.beginners | Postings from September 2009

Re: push and split

Thread Previous | Thread Next
From:
Noah Garrett Wallach
Date:
September 17, 2009 13:24
Subject:
Re: push and split
Message ID:
4AB29AF2.6000904@enabled.com
Chas. Owens wrote:
> On Thu, Sep 17, 2009 at 14:05, Noah Garrett Wallach
> <noah-list@enabled.com> wrote:
>> Hi there,
>>
>> I am attempting to read a text file in to two array variables.
>>
>> --- text file ---
>> hostname1 ip1
>> hostname2 ip2
>>
>> --- text file ---
>>
>>
>> so basically I would like to have the items in column become an the elements
>> of an array @routers
>>
>> and then the items in column two in an array variable of @ips
>>
>> I suppose I could use split and push to do that but how?
> snip
> 
> You can use split to create an array of fields in the line:
> 
> my @fields = split " ", $record;
> 
> and then you can use two calls to push to add the elements to the
> desired arrays:
> 
> push @routers, $fields[0];
> push @ips, $fields[1];
> 
> But I would probably use an array of hashrefs like this:
> 
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> 
> my @fields = qw/router ip/;
> my @machines;
> while (<DATA>) {
> 	my %record;
> 	@record{@fields} = split;
> 	push @machines, \%record;
> }
> 
> print "The second router is $machines[1]{router}\n",
> 	"The third IP is $machines[2]{ip}\n";
> 
> __DATA__
> foo 10.0.0.1
> bar 10.0.0.2
> baz 10.0.0.3
> 
> 

thats really  cool


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