【问题标题】:Perl split arrayPerl 拆分数组
【发布时间】:2014-06-21 20:24:17
【问题描述】:

我是 Perl 新手,我想编写一个简单的程序来读取输入文件并计算该文件的字母,这是我的代码:

 #!/usr/bin/perl

 $textfile = "example.txt";
 open(FILE, "< $textfile");

 @array = split(//,<FILE>);
 $counter = 0;
 foreach(@array){
      $counter = $counter + 1;
 }

 print "Letters: $counter";

此代码向我显示了字母的数量,但仅适用于我的输入文件的第一段,它不适用于超过一个段落,任何人都可以帮助我,我不知道问题 =( 谢谢

【问题讨论】:

    标签: arrays perl file split


    【解决方案1】:
    • 你只读过一行。
    • 您计算的是字节数(可以使用-s),而不是字母。

    修复:

    my $count = 0;
    while (<>) {
       $count += () = /\pL/g;
    }
    

    【讨论】:

    • hm,我用 while() {$count += () ...... - 循环替换了 foreach 循环,不起作用,不要给我看任何东西
    • @user3340823,在你的情况下是while (&lt;FILE&gt;) ...
    【解决方案2】:

    你的代码是一种相当复杂的方法:

    #!/usr/bin/perl
    
    # Always use these
    use strict;
    use warnings;
    
    # Define variables with my
    my $textfile = "example.txt";
    # Lexical filehandle, three-argument open
    # Check return from open, give sensible error
    open(my $file, '<', $textfile) or die "Can't open $textfile: $!"
    
    # No need for an array.
    my $counter = length <$file>;
    
    print "Letters: $counter";
    

    但是,正如其他人指出的那样,您计算的是 bytes 而不是 characters。如果您的文件是 ASCII 或 8 位编码,那么您应该没问题。否则你应该看看perluniintro

    【讨论】:

      【解决方案3】:

      这是使用模块完成工作的另一种方法..

      # the following two lines enforce 'clean' code
      use strict;
      use warnings;
      
      # load some help (read_file)
      use File::Slurp;
      
      # load the file into the variable $text
      my $text = read_file('example.txt');
      
      #get rid of multiple whitespace and linefeed chars # ****
      # and replace them with a single space             # ****
      $text =~ s/\s+/ /;                                 # ****
      
      # length gives you the length of the 'string' / scalar variable
      print length($text);
      

      您可能想要注释掉标记为“****”的行 和代码一起玩......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-01
        • 2013-12-18
        相关资源
        最近更新 更多