How do I count the characters, words, and lines in a file, using Perl?

前端 未结 10 1425
醉酒成梦
醉酒成梦 2020-12-31 03:21

What is a good/best way to count the number of characters, words, and lines of a text file using Perl (without using wc)?

10条回答
  •  忘掉有多难
    2020-12-31 03:31

    To be able to count CHARS and not bytes, consider this:
    (Try it with Chinese or Cyrillic letters and file saved in utf8)

    use utf8;
    
    my $file='file.txt';
    my $LAYER = ':encoding(UTF-8)';
    open( my $fh, '<', $file )
      || die( "$file couldn't be opened: $!" );
    binmode( $fh, $LAYER );
    read $fh, my $txt, -s $file;
    close $fh;
    
    print length $txt,$/;
    use bytes;
    print length $txt,$/;
    

提交回复
热议问题