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

Re: push and split

Thread Previous | Thread Next
Chas. Owens
September 17, 2009 11:16
Re: push and split
Message ID:
On Thu, Sep 17, 2009 at 14:05, Noah Garrett Wallach
<> 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?

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:


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";


Chas. Owens
The most important skill a programmer can have is the ability to read.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About