CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



kevet
Novice

May 16, 2014, 3:36 AM

Post #1 of 4 (2807 views)
How do read a file to muti array ? Can't Post

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

Post #2 of 4 (2771 views)
Re: [kevet] How do read a file to muti array ? [In reply to] Can't Post

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

Post #3 of 4 (2762 views)
Re: [BillKSmith] How do read a file to muti array ? [In reply to] Can't Post

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

Post #4 of 4 (2756 views)
Re: [Laurent_R] How do read a file to muti array ? [In reply to] Can't Post

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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives