A
adamomitcheney
Hi all,
I'm trying to write a program that loops through a file, extracts time,
date and data from each line then adds the data to a hash, keyed on
time, a reference to which is stored in another hash, keyed on date.
My first attempt looked something like this:
########################################
my $cclicusagebydate;
foreach my $line (@slurpedfile)
{
$line =~ m%(.+?),(.+?),(.+?)%;
my $date = $1;
my $time = $2;
my $cc = $3;
$cclicusagebydate = {$date =>{$time => $cc}};
}
This, of course, failed because I was allocating a new reference with
each iteration of the loop... If I replace the '$cclicusagebydate ='
line with:
$cclicusagebydate->{$date}->{$time} = $cc;
it fails again because I haven't declared $cclicusagebydate as a
hash...
As I see it, there are two options:
1 - put in a line like:
$cclicusagebydate = {'blah' => {'blah' => 'blah'}};
before the foreach loop to define the reference(s), or
2 - put the following into the foreach loop:
$cclicusagebydate = {$date =>{$time => $cc}} unless
ref($cclicusagebydate);
$cclicusagebydate->{$date}->{$time} = $cc;
Am I right - are these the (only) two options? Is there a better way to
make it work the way I hope? If not, which of these two is better?
Thanks.
Adam...
I'm trying to write a program that loops through a file, extracts time,
date and data from each line then adds the data to a hash, keyed on
time, a reference to which is stored in another hash, keyed on date.
My first attempt looked something like this:
########################################
my $cclicusagebydate;
foreach my $line (@slurpedfile)
{
$line =~ m%(.+?),(.+?),(.+?)%;
my $date = $1;
my $time = $2;
my $cc = $3;
$cclicusagebydate = {$date =>{$time => $cc}};
}
This, of course, failed because I was allocating a new reference with
each iteration of the loop... If I replace the '$cclicusagebydate ='
line with:
$cclicusagebydate->{$date}->{$time} = $cc;
it fails again because I haven't declared $cclicusagebydate as a
hash...
As I see it, there are two options:
1 - put in a line like:
$cclicusagebydate = {'blah' => {'blah' => 'blah'}};
before the foreach loop to define the reference(s), or
2 - put the following into the foreach loop:
$cclicusagebydate = {$date =>{$time => $cc}} unless
ref($cclicusagebydate);
$cclicusagebydate->{$date}->{$time} = $cc;
Am I right - are these the (only) two options? Is there a better way to
make it work the way I hope? If not, which of these two is better?
Thanks.
Adam...