Chinaunix

标题: 一个Perl练习 [打印本页]

作者: petercheng750    时间: 2010-04-14 11:50
标题: 一个Perl练习
我正在学Perl,看的是第四版的<erl语言入门> ;
今天做了一个练习,感觉有点不对劲,是第四章的第一个练习,题目如下:
写一个名为&total 的子程序,返回一列数字的和.
我的代码如下:
  1. #!/usr/bin/perl -w
  2. #chapter 4 exercise 1

  3. sub total{
  4.         my $total=0;
  5.         chomp(@_);
  6.         foreach (@_){
  7.                 $total+=$_;
  8.         }
  9.         $total;
  10. }
  11. my @terry = qw ( 1 2 3 4 5 );
  12. $count=total(@terry);
  13. print "the total of \@terry is $count\n";
  14. print "==============\n";
  15. my $user_stdin=total(<stdin>);
  16. print "the total of \@user is $user_stdin\n";
复制代码
我的问题是,当我的操作如下有空格或者直接回车的时候会出现警告)
  1. [root@test chapter4]# ./ex4_1.pl
  2. the total of @terry is 15
  3. ==============
  4. 1
  5. 2

  6. 3
  7. 4

  8. 5
  9. Argument "" isn't numeric in addition (+) at ./ex4_1.pl line 8, <stdin> line 7.
  10. Argument " " isn't numeric in addition (+) at ./ex4_1.pl line 8, <stdin> line 7.
  11. the total of @user is 15
复制代码
我想请教下是不是有什么函数或者其他什么的可以把警告去掉?
作者: yybmsrs    时间: 2010-04-14 12:12
警告是因为输入有空的,不是数字。把-w去掉就可以了。
作者: petercheng750    时间: 2010-04-14 12:16
回复 2# yybmsrs


    我一开始以为有像chomp那样消除回车之类的函数去消除列表中的空格,但我想了下好像Perl会自动转换标量的数字和字符,所以一时间没反应过来,O(∩_∩)O~呵呵
作者: blackold    时间: 2010-04-14 12:18

作者: hp_truth    时间: 2010-04-15 21:54
回复 1# petercheng750


    这种错误是perl里面很常见的一种错误, 一般是这个变量没有有效值。 chomp只是把行尾的回车去掉。 空格可以用 m/^\s*$/ 来识别。
   Perl程序中最好加上 use strict;  use warnings; 这样有一些错误会很快查出来。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2