
Chris Charley
User
Feb 25, 2013, 7:29 PM
Post #3 of 7
(288 views)
|
|
Re: [manchester] Extracting Data from a File and Tabulating It
[In reply to]
|
Can't Post
|
|
I found using a hash of hashes data structure worked best for me. I made the assumption that any name occurred only once in any file. #!/usr/bin/perl use strict; use warnings; use List::Util qw/ max /; my @files = qw/ o33.txt o44.txt o55.txt o66.txt /; my %data; for my $file (@files) { open my $fh, "<", $file or die "Unable to open '$file'. $!"; while (<$fh>) { my ($name, $count) = split; $data{$name}{$file} = $count; } close $fh or die "Unable to close '$file'. $!"; } my @names = sort keys %data; my $name_len = 1 + max map length, @names; my $file_len = 1 + max map length, @files; my $format = "%-${name_len}s" . "%${file_len}s" x @files . "\n"; printf $format, 'Name', @files; # print header for my $name (@names) { printf $format, $name, map $data{$name}{$_} || 0, @files; } This produced this output. C:\Old_Data\perlp>perl t11.pl Name o33.txt o44.txt o55.txt o66.txt alpha 3 6 0 0 bravo 2 0 2 0 charlie 1 9 0 4 delta 0 2 4 0 echo 0 0 0 1 Here is the structure of the hash of hashes. $VAR1 = { 'delta' => { 'o44.txt' => '2', 'o55.txt' => '4' }, 'alpha' => { 'o44.txt' => '6', 'o33.txt' => '3' }, 'bravo' => { 'o33.txt' => '2', 'o55.txt' => '2' }, 'charlie' => { 'o66.txt' => '4', 'o44.txt' => '9', 'o33.txt' => '1' }, 'echo' => { 'o66.txt' => '1' } };
(This post was edited by Chris Charley on Feb 26, 2013, 5:33 AM)
|