Front page | perl.beginners |
Postings from September 2009
Re: push and split
Thread Previous
|
Thread Next
From:
Steve Bertrand
Date:
September 17, 2009 12:11
Subject:
Re: push and split
Message ID:
4AB289D0.4080002@ibctech.ca
Noah Garrett Wallach wrote:
> Steve Bertrand wrote:
>> 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?
>>
>> What have you tried?
>>
>> After you've read the following, post back here with what you've tried,
>> and with any further questions:
>>
>> perldoc -f split
>> perldoc -f push
>>
>> Also, if you are trying to do what I think you are doing, you may want
>> to look at using a hash instead:
>>
>> $router_hash{ hostname1 } = 'ip_addr';
>>
>> Steve
> okay I will got the Hash route - thanks
Pay close attention to what Chas said about hashes that I didn't mention.
Hashes contain unique keys. If your file has two entries of a router
with the same name, eg:
router1 10.0.10.1
router2 10.0.10.2
router1 10.0.10.3
...you will have only one entry for router1 in the hash, and the value
for that entry will be the IP address that your program worked with last
(ie. 10.0.10.3).
Another thing, as Chas pointed out, hashes are unorganized, which means
that the order of retrieval is almost always different than the order of
insertion:
#!/usr/bin/perl
use warnings;
use strict;
my %router_hash;
while ( my $entry = <DATA> ) {
my ( $router, $ip ) = split /\s+/, $entry;
next if ! defined $ip;
$router_hash{ $router } = $ip;
}
while ( my ( $router, $ip ) = each %router_hash ) {
print "$router => $ip\n";
}
__DATA__
router1 10.0.10.1
router2 10.0.10.2
router3 10.0.10.3
...prints:
dump % ./order.pl
router1 => 10.0.10.1
router3 => 10.0.10.3
router2 => 10.0.10.2
Thread Previous
|
Thread Next