Reputation: 43
So I have the following code:
while (my $line = <$data>){
my $fields = split /,/, $line;
my $name = fields[0];
my $nickname = fields[1];
my $occurences = fields[2];
my $number = fields[3];
# I need to push it like this so that $occurences are in numerical order, i.e: 0,1,2,....,10
push @{$hash{$name}{$nickname}}, {$occurences=>$number};
}
for my $name (keys %hash) {
for my $nickname (keys %{$hash{$name}}) {
for my $value (keys @{$hash{$name}{$nickname}}) {
print "Value is Occurences: $value\n";
}
}
}
So I can print out the $occurences by doing that thing above but how do I print out the $number? I can't seem to figure out how to print $number.
Input data:
Name,Nickname,Occurences,Number
BobWill,bob,1,10
BobWill,bob,1,9
BobWill,bob,1,2
BobWill,bob,2,3
BobWill,bob,6,5
BobWill,bob,3,7
BobWill,will,1,10
BobWill,will,1,9
BobWill,will,1,2
BobWill,will,2,3
BobWill,will,3,5
BobWill,will,3,7
Danny,dan,10,2
Danny,dan,1,3
Danny,dan,8,9
Output Expected:
Value is Occurences: 1
Number is: 10
Value is Occurences: 1
Number is: 9
Value is Occurences: 1
Number is: 2
Value is Occurences: 2
Number is: 3
.
.
.
"Value is Occurences: #", The # should be in increasing order.
Upvotes: 0
Views: 83
Reputation: 6798
Perhaps following code demonstrates how desired result can be achieved
use strict;
use warnings;
use feature 'say';
my @fields = split ',', <DATA>;
my %hash;
while(<DATA>) {
chomp;
my($name,$nickname,$occurence,$number) = split ',';
push @{$hash{$name}{$nickname}{$occurence}},$number;
}
for my $name (keys %hash) {
for my $nickname (keys %{$hash{$name}}) {
for my $occurence (sort {$a <=> $b} keys %{$hash{$name}{$nickname}}) {
say "$name:$nickname:$occurence:"
. join(',',sort {$a <=> $b} @{$hash{$name}{$nickname}{$occurence}});
}
}
}
__DATA__
Name,Nickname,Occurences,Number
BobWill,bob,1,10
BobWill,bob,1,9
BobWill,bob,1,2
BobWill,bob,2,3
BobWill,bob,6,5
BobWill,bob,3,7
BobWill,will,1,10
BobWill,will,1,9
BobWill,will,1,2
BobWill,will,2,3
BobWill,will,3,5
BobWill,will,3,7
Danny,dan,10,2
Danny,dan,1,3
Danny,dan,8,9
Produced output
BobWill:will:1:2,9,10
BobWill:will:2:3
BobWill:will:3:5,7
BobWill:bob:1:2,9,10
BobWill:bob:2:3
BobWill:bob:3:7
BobWill:bob:6:5
Danny:dan:1:3
Danny:dan:8:9
Danny:dan:10:2
Upvotes: 2