0

I'm new in Perl, I want to write a simple program which reads an input-file and count the letters of this file, this is my code:

 #!/usr/bin/perl

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

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

 print "Letters: $counter";

this code shows me the number of letters, but only for the first paragraph of my Input-File, it doesn't work for more than one paragraph, can anyone help me, i don't know the problem =( thank you

3 Answers 3

2
  • You only ever read one line.
  • You count bytes (for which you could use -s), not letters.

Fix:

my $count = 0;
while (<>) {
   $count += () = /\pL/g;
}
Sign up to request clarification or add additional context in comments.

2 Comments

hm, I replaced the foreach-loop, with the while(<>) {$count += () ...... - loop, doesn't work, don't show me anything
@user3340823, in your case it'd be while (<FILE>) ...
1

You code is a rather over-complicated way of doing this:

#!/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";

But, as others have pointed out, you're counting bytes not characters. If your file is in ASCII or an 8-bit encoding, then you should be fine. Otherwise you should look at perluniintro.

Comments

-1

Here's an alternative aproach using a module to do the work ..

# 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);

you might want to comment out the lines marked '****' and play with the code...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.