Question Locked

File Handling - Perl

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hi,
I have written a code to count the no. of lines, words and characters in a file. When I execute the xcript, I always get 0 lines, 0 words and charcters equal to the no. of lines.

The script is below:
#!/usr/bin/perl

$l=0;
$w=0;
$chr=0;
open (FILE,"C:/nrk/programming/perl/sample.txt");
@arr=;
for($i=0;$i<$x;$i++)
{
if ($arr[$i] eq "\n" || $arr[$i] eq " " || $arr[$i] eq "!")
{
$w++;
}
if ($arr[$i] eq "\n")
{
$l++;
}
else
{
$chr++;
}
}
print ("The text file has $l lines, $w words and $chr characters\n");

The contents of the file "sample.txt" is as below:
hello everyone!!
wish you all good
luck
for your future.

Could anyone help?
Thanks,
Kali.

6 replies

by deshpandeamit19

the problem is in the line
for($i=0;$i<$x;$i++)
perl can;t find the decimal value for $x so it is showing wrong answer .

just out 100 in this loop
for($i=0;$i<100;$i++)
u can get the count ,
but the problem is u will not get the count of all the char in the file . the count will be for first 100 chars .
i am trying some logics for this also

1> u can count the number of array elements then set the loop of the same....
i am trying with this option

by deshpandeamit19

the problem is in the line
for($i=0;$i<$x;$i++)
perl can;t find the decimal value for $x so it is showing wrong answer .

just out 100 in this loop
for($i=0;$i<100;$i++)
u can get the count ,
but the problem is u will not get the count of all the char in the file . the count will be for first 100 chars .
i am trying some logics for this also

1> u can count the number of array elements then set the loop of the same....
i am trying with this option

Thanks,
~amit

by deshpandeamit19

if the file has
=========================
this is perl
i want to do this just now
==========================

if u try to store the file in an Array
the count will give u "2"

array will store line 1 == @arr[1]
line 2 == @arr[2]

by rashkovsky

foreach $line (@content){
$count++;
@words = split (/\s/,$line);
$wordscount += @words;
foreach $char (@words){
@chars = split (//,$char);
$charcount+= @chars;
}
}

by daveo2000

Get in the habit of starting your scripts with:

#!/usr/local/bin/perl -w
use strict;

This will point out undefined variables and the like. In this case, you have not defined $x nor do you ever modify it. The loop will probably run for one iteration.

Next, you need a better understanding of the "@arr=" construct. That reads each complete line into an array element. Therefore, $arr[0] is "hello everyone!!\n"

You would be better served by using the loop:

while ($line = ) {
$l++;
$c+= len($line);
my @words = (split("\s", $line));
$w += $#words;
}

or something like that.

This discussion is closed to new replies.