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: Re: [manchester] Extracting Data from a File and Tabulating It : Edit Log



Chris Charley
User

Feb 25, 2013, 7:29 PM


Views: 684
Re: [manchester] Extracting Data from a File and Tabulating It

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.

Code
  #!/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.

Code
   
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.

Code
  $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)


Edit Log:
Post edited by Chris Charley (User) on Feb 25, 2013, 7:36 PM
Post edited by Chris Charley (User) on Feb 25, 2013, 7:52 PM
Post edited by Chris Charley (User) on Feb 26, 2013, 5:26 AM
Post edited by Chris Charley (User) on Feb 26, 2013, 5:33 AM


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

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