I've been hesitating to post this question. It's a follow up re. my question of this morning
Split pattern doesn't match last line of file. This time I'm less sure how to define the title.
I trying to write a script that summarizes data from text files. Right now I've got a problem to make calculations with data that's somewhere in the hash? I'm really puzzled.
Code produced so far is mentioned below. It all works well with the data except that I would like to
print the result from the "C" and "D" values. I've tried but can't get to my data. From out of the
foreach loop or can I? Any help or reference to how to work with hashes is appreciated.
Gert
#!/usr/bin/perl
use strict;
use vars qw !$file!;
chdir '/test/' or die "Cannot change to /test: $!";
foreach $file ( readdir DH ) {
}
foreach $file ( glob "*.txt" ) {
open FILE, '<', $file;
my %saldi;
while (<FILE>) {
chomp;
next unless $_;
my @cellen = ( split /,/, )[ 3, 4 ];
next unless $cellen[0] && $cellen[1];
$saldi{ $cellen[0] } += $cellen[1];
}
$file =~ m/^(\S+)\.txt/;
print "$1\n";
foreach my $name ( keys %saldi ) {
printf "\t$name\t" . "%16s", &big_money( $saldi{$name} ) . "\n
+";
}
close FILE;
}
closedir DH;
sub big_money { #Learning Perl
my $number = sprintf "%.2f", shift @_;
#Add one comma each time though the do-nothing loop
1 while $number =~ s/^(-?\d+)(\d\d\d)/$1,$2/;
#Put the dollar sign in the right place
$number =~ s/^(-?)/$1/;
$number;
}
Data_1.txt
394,eur,2006,D,18.20
394,eur,2006,D,22
394,eur,2006,C,25
Data_2.txt
494,eur,2006,C,25
494,eur,2006,D,79
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.