Home: Perl Programming Help: Beginner:
How do read a file to muti array ?



kevet
Novice

May 16, 2014, 3:36 AM


Views: 3319
How do read a file to muti array ?

If I have a file like this ..

7odc 54 249
7odc 150 190
7odc 293 374
2qud 54 87
2qud 100 104
1d2s 99 97
3rc3 167 174
3rc3 186 184
3rc3 445 425


How to I read this content into different arrays ?
Like show this .....

7odc => array1 = (54 ,249, 150, 190, 293, 374 )
2qud => array2 = (54 ,87, 100, 104 )
1d2s => array3 = (99, 97)
3rc3 => array4 = (167,174,186, 184,445,425)

my code is below, where can I fix ... thanks@@!


Code
my $temp = "7odc"; 

while(<Link>){
chomp;
my @data = split/\s+/;
my @net;
my $id = $data[0];

if($id eq $temp){
push @net, $data[1];
push @net, $data[2];
}
elsif($id ne $temp){
$temp = $id;
return;
}

print @net;
print "\n";
}


BillKSmith
Veteran

May 16, 2014, 5:00 AM


Views: 3283
Re: [kevet] How do read a file to muti array ?

Use a hash-of-arrays:

Code
use strict; 
use warnings;
my %nets;

while(<DATA>){
chomp;
my ($id, @data) = split/\s+/;
push @{$nets{$id}}, @data;
}
my $count=0;
while (my ($id, $data) = each %nets) {
local $" = ', ';
$count++;
print "$id => array$count = (@$data)\n"
}
__DATA__
7odc 54 249
7odc 150 190
7odc 293 374
2qud 54 87
2qud 100 104
1d2s 99 97
3rc3 167 174
3rc3 186 184
3rc3 445 425


OUTPUT:


Code
C:\Users\Bill\perl\guru>kevet2.pl 
3rc3 => array1 = (167, 174, 186, 184, 445, 425)
2qud => array2 = (54, 87, 100, 104)
7odc => array3 = (54, 249, 150, 190, 293, 374)
1d2s => array4 = (99, 97)

Good Luck,
Bill


Laurent_R
Veteran / Moderator

May 16, 2014, 9:49 AM


Views: 3274
Re: [BillKSmith] How do read a file to muti array ?

It might not matter, but using a hash of arrays will not preserve the order of the original file.


BillKSmith
Veteran

May 16, 2014, 1:16 PM


Views: 3268
Re: [Laurent_R] How do read a file to muti array ?

Worse yet, the Id's and array names do not match up as shown in the original spec. I chose to postpone that issue until it became a problem. I probably should have mentioned it.
Good Luck,
Bill