cancel
Showing results for 
Search instead for 
Did you mean: 

perl script need to be modified

kiran1977
Occasional Contributor

perl script need to be modified

open (INP, "while () {
chomp;
my ($key, $x) = (split /\s*\|\s*/)[2,18];
if ($x == 4) {
$count{$key} +=1 ;
}
elsif ($x == 6) {
$count1{$key} +=1 ;
}
elsif ($x == 7) {
$count2{$key} +=1;
}
elsif ($x ==8) {
$count3{$key} += 1;
}
elsif ($x == 9) {
$count4{$key} += 1;
}
}
close INP;
foreach my $i (sort keys %count,%count1,%count2,%count3,%count4) {
print"SN=$i|C4:$count{$i}|C6:$count1{$i}|C7:$count2{$i}|C8:$count3{$i}|C9:$count4{$i}\n";
}

field=2 store key and field=18 Coupon type.

i need the output as unique store with approipiate number of coupon type in it("4","6","7","8","9")

am getting output as :
SN=100 |C4:1|C6:|C7:2|C8:|C9:1
SN=100 |C4:1|C6:|C7:2|C8:|C9:1
SN=100 |C4:1|C6:|C7:2|C8:|C9:1

Expected Result:
SN=100 |C4:1|C6:|C7:2|C8:|C9:1
only once it should print .

and some of the store numbers are getting trailed SN=1 |C4:|C6:|C7:|C8:|C9:

please can you rework the script and make it succseful.

Great Thanks

1 REPLY
Hein van den Heuvel
Honored Contributor

Re: perl script need to be modified

Try this:

%valid_coupons = qw ( 4 0 6 0 7 0 8 0 9 0 );
$file = "x.txt";
open (INP, "<$file" ) or die "$file: $!";
while () {
my ($key, $coupon) = (split /\s*\|\s*/)[2,18];
$stores{$key}++;
$counters{"$key $coupon"}++ if exists $valid_coupons{$coupon}
}
close INP;
foreach my $key (sort keys %stores) {
print "SN=$key";
foreach my $coupon (sort keys %valid_coupons) {
printf ("|C%s:%d", $coupon, $counters{"$key $coupon"});
}
print "\n";
}

if any coupon is valid, then drop the initial %valid_coupons line and
replace the line with $counters..++ with:

$valid_coupons{$coupon}++;
$counters{"$key $coupon"}++;

The results for the attached file was:
SN=100|C4:2|C6:0|C7:0|C8:0|C9:0
SN=200|C4:0|C6:1|C7:1|C8:2|C9:1
SN=300|C4:1|C6:1|C7:2|C8:0|C9:0

If you need further help, then be sure to attach a sample input file on a future reply.

hth,
Hein.