John W. Krahn wrote:
Richard Lee wrote:
just trying to learn pack/unpack function in perl..
http://perldoc.perl.org/perlpacktut.html
You *should* have the documentation for Perl installed on your hard
drive which will be more relevant to the version of Perl you are using.
I thought i followed pretty much to the teeth from the tutorial
itself and when I type them into my linux box , it didn't exactly
work the way
I expected them to.. What am I doing wrong?
[EMAIL PROTECTED] ~]# cat -A pack_test2.pl
cat -A? You're really trying to make it difficult to just copy and
run your code?
#!/usr/bin/perl$
$
use strict;$
use warnings;$
$
my $tot_income;$
my $tot_expend;$
use POSIX;$
$
my $date = POSIX::strftime("%m/%d/%Y", localtime);$
$
while (<DATA>) {$
my($date, $desc, $income, $expend) = unpack("A10 A27 A7 A*", $_);$
Your unpack() format defines the fields as:
01/24/2001 Ahmed's Camel Emporium 1147.99
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 235.00
^ ^ ^ ^
123456789012345678901234567890123456789012345678901234567890
The second field includes leading whitespace which you don't need.
The third field is not long enough and cuts off the decimal portion of
the number. The fourth field includes the decimal portion from the
third field which in numerical context will be interpreted as the
fourth field instead of the actual fourth field.
You probably want something like this instead:
unpack 'A11 A26 A9 A*', $_;
$tot_income += $income;$
$tot_expend += $expend;$
To suppress the "isn't numeric" warning you can do this:
$tot_income += $income || 0;
$tot_expend += $expend || 0;
print_this($tot_income,$tot_expend);$
}$
$
sub print_this {$
my($tot_income,$tot_expend) = @_;$
$tot_income = sprintf("%.2f", $tot_income); # Get them into $
$tot_expend = sprintf("%.2f", $tot_expend); # "financial" format$
print pack("A10 A27 A7 A*", $date, "Totals", $tot_income,
$tot_expend);$
And don't forget to add a newline at the end of each output line:
print pack( 'A10 A27 A7 A*', $date, 'Totals', $tot_income,
$tot_expend ), "\n";
}$
$
__END__$
01/24/2001 Ahmed's Camel Emporium 1147.99$
01/28/2001 Flea spray 24.99$
01/29/2001 Camel rides to tourists 235.00$
But it's not working out well..
[EMAIL PROTECTED] ~]# ./!$
./././././././pack_test2.pl
Argument "" isn't numeric in addition (+) at
./././././././pack_test2.pl line 14, <DATA> line 1.
Argument "" isn't numeric in addition (+) at
./././././././pack_test2.pl line 14, <DATA> line 2.
07/19/2008Totals 0.00
1147.9907/19/2008Totals 0.00
1172.9807/19/2008Totals 235.00 [EMAIL PROTECTED] ~]#
John
Thanks John and others for explanation. I understand now.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/