#!/usr/bin/perl
use warnings;
use strict;
use Getopt::Long;
my ($confFile, $debug, $usage);
GetOptions( "conf=s" => \$confFile ,
"debug" => \$debug);
$usage = "--conf=<input-conf-file> --debug";
my %components;
# open conf file
open (CONF_FILE, "$confFile") ||
die "Failed to open confFile=$confFile\n";
# read file contents
sub readFile {
my @records; # list of all records in file
my $record; # single record in @records
undef $/;
@records = split(/\cM\cJ/, <CONF_FILE>);
foreach $record (@records) {
my ($com, $subcat, $cat, $summary, $steps, $expRes, $pri, @temp);
my %entry;
chomp $record;
@temp = split (/\cJ/, $record); #ger rid of embedded newline
$record = join '', @temp; #setup record again after removal of newlines
print "Read: $record\n" if $debug;
# parse record into individual fields and put in a hash
($com, $subcat, $cat, $summary, $steps, $expRes, $pri) = split (/,/, $record);
$entry{com} = $com;
$entry{subcat} = $subcat;
$entry{cat} = $cat;
$entry{summary} = $summary;
$entry{steps} = $steps;
$entry{expRes} = $expRes;
$entry{pri} = $pri;
print "\tParsed fields: $com ;; $subcat;; $cat;; ",
"$summary;; $steps;; $expRes;; $pri\n" if $debug;
print "\tParsed fields: $entry{com} ;; $entry{subcat};; $cat;; ",
"$summary;; $steps;; $expRes;; $pri\n" if $debug;
# push this hash 'entry' into the list in hash-of-hash
# this hash 'components' is organized as components{Component1}{Priority}
# and this entry contains a list of hashes of the type 'entry' (above)
push @{ $components{$com}{$pri} }, \%entry; ########## QUESTION BELOW
}
}
sub printOut {
my ($component, $pri);
my @records;
my $rec = {};
foreach $component ( keys %components ) {
foreach $pri (sort keys %{ $components{$component} } ) {
print "Printing $component/$pri\n" if $debug;
@records = @{ $components{$component}{$pri} } ;
my $count = 1;
foreach $rec (@records) {
my %e = %{ $rec };
print "$count: $e{com}, $e{pri}, $e{summary}\n";
}
}
}
}
sub main {
&readFile();
&printOut();
}
&main();
[\code]
Thanks. I cleaned it up and the result is much better than my previous hasty
and kludgy attempt. Now the basic thing works. However one question I have is why do
I need to pass the %entry by ref in last line of readFile() (see NOTE in code)?
If I don't pass by ref then I think the hash somehow gets converted to
string (key1 value1 key2 value2 ... etc.). The way I'm doing it, is that the
correct way of adding the hash to a list (and also of extracting) ?
Thanks for the help :)