+ -
当前位置:首页 → 问答吧 → 读取文件的简单程序报错了求指点

读取文件的简单程序报错了求指点

时间:2010-10-06

来源:互联网

  1. use strict;
  2. use warnings;

  3. main(@ARGV);

  4. sub main
  5. {
  6.     my $line;
  7.     open FH,"short.txt";
  8.     while ($line=<FH>){
  9.         print if($line =~ m|/|);
  10.     }
  11.     close FH;
  12. }
  13. sub message
  14. {
  15.     my $m=shift or return;
  16.     print "$m\n";
  17. }
复制代码
cat short.txt
  1. This page describes the syntax of regular expressions in Perl.

  2. If you haven't used regular expressions before, a quick-start
  3. introduction is available in perlrequick, and a longer tutorial
  4. introduction is available in perlretut.

  5. For reference on how regular expressions are used in matching
  6. operations, plus various examples of the same, see discussions of "m//",
  7. "s///", "qr//" and "??" in "Regexp Quote-Like Operators" in perlop.

  8. Matching operations can have various modifiers. Modifiers that relate to
  9. the interpretation of the regular expression inside are listed below.
  10. Modifiers that alter the way a regular expression is used by Perl are
  11. detailed in "Regexp Quote-Like Operators" in perlop and "Gory details of
  12. parsing quoted constructs" in perlop.
复制代码
perl -w readshort.pl
Use of uninitialized value in print at readshort.pl line 31, <FH> line 8.
Use of uninitialized value in print at readshort.pl line 31, <FH> line 9.

如果用$_就没事
  1. use strict;
  2. use warnings;

  3. main(@ARGV);

  4. sub main
  5. {
  6.     my $line;
  7.     open FH,"short.txt";
  8.     while ($_=<FH>){
  9.         print if($_ =~ m|/|);
  10.     }
  11.     close FH;
  12. }
  13. sub message
  14. {
  15.     my $m=shift or return;
  16.     print "$m\n";
  17. }
  18. #END
复制代码
perl -w readshort.pl
operations, plus various examples of the same, see discussions of "m//",
"s///", "qr//" and "??" in "Regexp Quote-Like Operators" in perlop.

作者: laohuanggua   发布时间: 2010-10-06

因为 while(<FH>) {} 等于 while (my $_ = <FH>) {}
要问为什么我估计是搞 Perl 那帮家伙太懒了,想少打几个字符,对于默认 $_ 为参数的函数也会很方便。而且以前 $_ 是不能 my 的

作者: zhlong8   发布时间: 2010-10-06