Perl hash给出严格的refs错误

时间:2014-06-05 22:03:46

标签: perl hash ref

我正在尝试编写代码,根据特定年份的月份和每年每月的总产出来增加销售收入,但是我的代码错了,而我现在只是被卡住了。

use strict;
use warnings;
my @newPlans = `cat plansSold.txt`;
my @oldPlans = `cat plansCancelled.txt`;
my %amounts;
for(@newPlans){
    chomp;
    my ($price,$billPeriod,$date) = (split /\;/, $_ )[4,5,7];
    my $montly = $price/$billPeriod;
    my ($f,$l) = (split /\-/, $date)[0,1];
    $montly = (split /\./, $montly)[0];
    $date = "$f\-$l";
    $amounts{$date} += $montly;
}
for my $date (sort keys %amounts) {
    print '.';
    print "$amounts{$date} : $_\n" for (sort keys %{ $amounts{$date} });
}

$ price,$ billPeriod,$ date如下。

7.95,1,2012-04
9.95,1,2012-06
19.95,12,2012-06
19.95,1,2014-02
12.95,3,2013-03
19.95,1,2014-01
18.95,1,2012-12
18.95,6,2012-12
18.95,1,2012-05

错误:

Can't use string ("6177") as a HASH ref while "strict refs" in use at revenueHistory.pl line 28.

这是这条线

for my $date (sort keys %amounts) {

我似乎无法弄清楚如何解决它。

2 个答案:

答案 0 :(得分:2)

这一行

print "$amounts{$date} : $_\n" for (sort keys %{ $amounts{$date} });

正在尝试将$amounts{$date}中的数字总数视为哈希引用,并且它不是。你已经总计了一个总计,并且你有一个数字,但是现在你希望它是一个哈希引用,这没有用。

你真正想做的是什么?

答案 1 :(得分:-2)

搞定了

use strict;
use warnings;
my @newPlans = `cat plansSold.txt`;
my @oldPlans = `cat plansCancelled.txt`;
my %amounts;
my $hold = 'tt';
for(@newPlans){
    chomp;
    my ($price,$billPeriod,$date) = (split /\;/, $_ )[4,5,7];
    my $montly = $price/$billPeriod;
    my ($f,$l) = (split /\-/, $date)[0,1];
    $montly = (split /\./, $montly)[0];
    $date = "$f\-$l";
    $amounts{$date}{$date} += $montly;
    #print "$price,$billPeriod,$date\n";
}
for my $date (sort keys %amounts) {
    print '.';
    print "$amounts{$date}{$date} : $_\n" for (sort keys %{ $amounts{$date}});
}