Richard Lee wrote:
>
> just trying to learn pack/unpack function in perl..
> 
> http://perldoc.perl.org/perlpacktut.html
> 
> 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
> #!/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*", $_);$
>         $tot_income += $income;$
>         $tot_expend += $expend;$
>         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);$
> }$
> $
> __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] ~]#

I think you're spacing your data out with tab characters. A tab is a single
character as far as unpack is concerned so things are getting mis-aligned.

The "Argument isn't numeric" warnings are because the income and expenditure
fields are blank. If you want the to default to zero you need to write

  defined and /\S/ or $_ = 0 for $tot_income, $tot_expend;

after the unpack.

You know that a literal space in the unpack pattern is ignored? If you want to
skip over a character use 'x'.

HTH,

Rob

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to